add breadcrumbs

This commit is contained in:
2024-05-18 13:16:57 +07:00
parent 6b3306bb96
commit db4419dc81
9 changed files with 421 additions and 59 deletions
+8
View File
@@ -40,3 +40,11 @@ func (s *Server) GetProduct(ctx context.Context, req *crm.GetProductReq) (*crm.P
}
return &crm.ProductRsp{Product: product}, nil
}
func (s *Server) GetBreadcrumbs(ctx context.Context, req *crm.GetBreadcrumbsReq) (*crm.BreadcrumbsRsp, error) {
breadcrumbs, err := s.storage.GetBreadcrumbs(ctx, req.Id)
if err != nil {
return nil, err
}
return &crm.BreadcrumbsRsp{Categories: breadcrumbs}, nil
}
+1 -11
View File
@@ -5,19 +5,9 @@ import (
"context"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
// todo
}
type Breadcrumb struct {
Name string `json:"name"`
URL string `json:"url"`
}
type IStorage interface {
GetCatalog(ctx context.Context) ([]*crm.Category, error)
GetPositions(ctx context.Context, id int64) ([]*crm.Product, error)
GetProduct(ctx context.Context, id int64) (*crm.Product, error)
GetBreadcrumbs(ctx context.Context, id int64) ([]*crm.Category, error)
}
@@ -65,3 +65,33 @@ func (s *storageFile) GetProduct(_ context.Context, id int64) (*crm.Product, err
}
return nil, ErrProductNotFound
}
func (s *storageFile) GetBreadcrumbs(_ context.Context, id int64) ([]*crm.Category, error) {
data, err := os.ReadFile("resources/catalog.json")
if err != nil {
return nil, err
}
var categories []*crm.Category
if err := json.Unmarshal(data, &categories); err != nil {
return nil, err
}
return getBreadcrumbs(categories, id), nil
}
func getBreadcrumbs(categories []*crm.Category, id int64) []*crm.Category {
for _, category := range categories {
if category.Id == id {
category.Children = nil
return []*crm.Category{category}
}
breadcrumbs := getBreadcrumbs(category.Children, id)
if len(breadcrumbs) != 0 {
res := make([]*crm.Category, 0, len(breadcrumbs)+1)
category.Children = nil
res = append(res, category)
res = append(res, breadcrumbs...)
return res
}
}
return nil
}