flamingo.me/flamingo-commerce/v3@v3.11.0/category/infrastructure/categoryServiceFixed.go (about) 1 package infrastructure 2 3 import ( 4 "context" 5 "sort" 6 7 "flamingo.me/flamingo-commerce/v3/category/domain" 8 9 "flamingo.me/flamingo/v3/framework/config" 10 ) 11 12 type ( 13 //CategoryServiceFixed - a secondary adapter for category service that returns simple categories based from configuration 14 CategoryServiceFixed struct { 15 mappedTree *domain.TreeData 16 mappedCategories map[string]*domain.CategoryData 17 } 18 19 configCat struct { 20 Code string 21 Name string 22 Sort int 23 Childs map[string]configCat 24 } 25 ) 26 27 var ( 28 _ domain.CategoryService = new(CategoryServiceFixed) 29 ) 30 31 // Inject - dingo injector 32 func (c *CategoryServiceFixed) Inject(config *struct { 33 Tree config.Map `inject:"config:commerce.category.categoryServiceFixed.tree"` 34 }) { 35 c.mapConfig(config.Tree) 36 } 37 38 func (c *CategoryServiceFixed) mapConfig(config config.Map) { 39 structure := make(map[string]configCat) 40 config.MapInto(&structure) 41 42 c.mappedCategories = make(map[string]*domain.CategoryData) 43 44 c.mappedTree = &domain.TreeData{ 45 CategoryCode: "root", 46 SubTreesData: c.getSubTree(structure), 47 } 48 49 } 50 51 func (c *CategoryServiceFixed) getSubTree(subs map[string]configCat) []*domain.TreeData { 52 var trees []*domain.TreeData 53 var sliceOfCategoryDto []configCat 54 for _, cat := range subs { 55 sliceOfCategoryDto = append(sliceOfCategoryDto, cat) 56 } 57 sort.Slice(sliceOfCategoryDto, func(i, j int) bool { 58 return sliceOfCategoryDto[i].Sort < sliceOfCategoryDto[j].Sort 59 }) 60 for _, cat := range sliceOfCategoryDto { 61 trees = append(trees, &domain.TreeData{ 62 CategoryCode: cat.Code, 63 CategoryName: cat.Name, 64 SubTreesData: c.getSubTree(cat.Childs), 65 }) 66 67 c.mappedCategories[cat.Code] = &domain.CategoryData{ 68 CategoryCode: cat.Code, 69 CategoryName: cat.Name, 70 } 71 } 72 73 return trees 74 } 75 76 // Tree a category 77 func (c *CategoryServiceFixed) Tree(ctx context.Context, activeCategoryCode string) (domain.Tree, error) { 78 if c.mappedTree == nil { 79 return nil, domain.ErrNotFound 80 } 81 return c.mappedTree, nil 82 } 83 84 // Get a category with more data 85 func (c *CategoryServiceFixed) Get(ctx context.Context, categoryCode string) (domain.Category, error) { 86 if cat, ok := c.mappedCategories[categoryCode]; ok { 87 return cat, nil 88 } 89 return nil, domain.ErrNotFound 90 }