bpiek/api/categories.go
Pavel Sinitsin e14d4b188b
Add new API and client modules for category and product management
This commit introduces new API and client modules that provide functionality for managing categories and products. It includes the creation of `.gitignore`, necessary data models, API endpoints, and client authentication using go-resty. This forms the foundation for further enhancements to the category and product management features.
2024-09-07 19:14:29 +03:00

78 lines
1.8 KiB
Go

package api
import (
"errors"
"gitea.24example.ru/spavelit/bpiek/model"
)
var categories []model.Category
var parentCategories []model.Category
func (a *Api) GetCategories() ([]model.Category, error) {
if len(categories) > 0 {
return categories, nil
}
parentCategoris, err := a.GetParentCategories()
if err != nil {
return nil, err
}
for _, category := range parentCategoris {
categoriesAndProduct, err := a.GetCategoriesAndProductsBySlugParentCategory(category.Slug)
if err != nil {
return nil, err
}
if len(categoriesAndProduct.Categories) != 0 {
categories = append(categories, categoriesAndProduct.Categories...)
}
}
return categories, nil
}
func (a *Api) GetParentCategories() ([]model.Category, error) {
if len(parentCategories) > 0 {
return parentCategories, nil
}
apiResponse, err := a.Client.HTTPClient.R().SetResult(&model.CategoryResponse{}).Get("client/catalog")
if err != nil {
return nil, err
}
if apiResponse.StatusCode() != 200 {
return nil, errors.New("failed to get categories")
}
result := apiResponse.Result().(*model.CategoryResponse).Categories
if len(result) == 0 {
return nil, errors.New("no categories found")
}
parentCategories = result
return parentCategories, nil
}
func (a *Api) GetCategoriesAndProductsBySlugParentCategory(slug string) (*model.CategoriesAndProductsBySlugParentCategoryResponse, error) {
apiResponse, err := a.Client.HTTPClient.
R().
SetResult(&model.CategoriesAndProductsBySlugParentCategoryResponse{}).
Get("client/category/" + slug + "/json")
if err != nil {
return nil, err
}
if apiResponse.StatusCode() != 200 {
return nil, errors.New("failed to get categories and products")
}
return apiResponse.Result().(*model.CategoriesAndProductsBySlugParentCategoryResponse), nil
}