flamingo.me/flamingo-commerce/v3@v3.11.0/product/infrastructure/fake/helper.go (about) 1 package fake 2 3 import ( 4 // embed test data file directly 5 _ "embed" 6 "encoding/json" 7 "errors" 8 "os" 9 "path/filepath" 10 "strings" 11 12 "flamingo.me/flamingo/v3/framework/flamingo" 13 14 searchDomain "flamingo.me/flamingo-commerce/v3/search/domain" 15 16 "flamingo.me/flamingo-commerce/v3/product/domain" 17 ) 18 19 // registerTestData returns files of given folder 20 func registerTestData(folder string, logger flamingo.Logger) map[string]string { 21 testDataFiles := make(map[string]string) 22 files, err := os.ReadDir(folder) 23 if err != nil { 24 logger.Info(err) 25 return testDataFiles 26 } 27 28 for _, file := range files { 29 if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") { 30 base := filepath.Base(file.Name())[:len(file.Name())-len(".json")] 31 testDataFiles[base] = filepath.Join(folder, file.Name()) 32 } 33 } 34 return testDataFiles 35 } 36 37 // unmarshalJSONProduct unmarshals product based on type 38 func unmarshalJSONProduct(productRaw []byte) (domain.BasicProduct, error) { 39 product := &map[string]interface{}{} 40 err := json.Unmarshal(productRaw, product) 41 42 if err != nil { 43 return nil, err 44 } 45 46 productType, ok := (*product)["Type"] 47 48 if !ok { 49 return nil, errors.New("type is not specified") 50 } 51 52 if productType == domain.TypeConfigurable { 53 configurableProduct := &domain.ConfigurableProduct{} 54 err = json.Unmarshal(productRaw, configurableProduct) 55 if err == nil { 56 return *configurableProduct, nil 57 } 58 } 59 60 if productType == domain.TypeBundle { 61 bundleProduct := &domain.BundleProduct{} 62 err = json.Unmarshal(productRaw, bundleProduct) 63 if err == nil { 64 return *bundleProduct, nil 65 } 66 } 67 68 simpleProduct := &domain.SimpleProduct{} 69 err = json.Unmarshal(productRaw, simpleProduct) 70 if err != nil { 71 return nil, err 72 } 73 74 return *simpleProduct, nil 75 } 76 77 //go:embed testdata/categoryFacetItems.json 78 var testdata []byte 79 80 func loadCategoryFacetItems(givenJSON string) ([]*searchDomain.FacetItem, error) { 81 82 var items []*searchDomain.FacetItem 83 84 if givenJSON != "" { 85 fileContent, err := os.ReadFile(givenJSON) 86 if err != nil { 87 return nil, err 88 } 89 90 err = json.Unmarshal(fileContent, &items) 91 if err != nil { 92 return nil, err 93 } 94 return items, nil 95 } 96 97 err := json.Unmarshal(testdata, &items) 98 if err != nil { 99 return nil, err 100 } 101 102 return items, nil 103 }