commit code

This commit is contained in:
2025-05-31 21:44:34 +08:00
parent bfca5d7d0b
commit ca373ad91f
19 changed files with 496 additions and 126 deletions

View File

@ -0,0 +1,73 @@
package logic
import (
"context"
"errors"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type GetFullCategoriesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetFullCategoriesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFullCategoriesLogic {
return &GetFullCategoriesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 获取某一个类别的完整类别(从根类别到当前类别的所有类别)
func (l *GetFullCategoriesLogic) GetFullCategories(in *category.GetCategoryRequest) (*category.GetFullCategoriesResponse, error) {
// 1. 参数校验
if in.Id == "" {
return nil, status.Error(codes.InvalidArgument, "分类ID不能为空")
}
// 2. 查询当前分类
current, err := l.svcCtx.CategoryModel.FindOne(l.ctx, in.Id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("分类不存在, ID: %s", in.Id)
return nil, status.Error(codes.NotFound, "分类不存在")
}
l.Logger.Errorf("数据库查询失败: %v", err)
return nil, status.Error(codes.Internal, "内部错误")
}
// 3. 初始化路径为当前分类名称
fullPath := current.Name
// 4. 循环获取父分类
parentID := current.ParentId
for parentID.Valid {
// 查询父分类
parent, err := l.svcCtx.CategoryModel.FindOne(l.ctx, parentID.String)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("父分类不存在, ID: %s", parentID.String)
break // 遇到不存在的父分类时停止循环
}
l.Logger.Errorf("查询父分类失败: %v", err)
break // 其他错误也停止循环
}
// 将父分类名称添加到路径前面
fullPath = parent.Name + "/" + fullPath
parentID = parent.ParentId // 准备查询上一级父分类
}
return &category.GetFullCategoriesResponse{
FullCategoryName: fullPath,
}, nil
}