package logic import ( "context" "strings" "godemo/category/category" "godemo/gateway/internal/svc" "godemo/gateway/internal/types" "github.com/zeromicro/go-zero/core/logx" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type CreateCategoryLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewCreateCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCategoryLogic { return &CreateCategoryLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CreateCategoryLogic) CreateCategory(req *types.CreateCategoryReq) (resp *types.CreateCategoryResp, err error) { // 1. 参数验证 if err := validateCreateRequest(req); err != nil { return nil, err } // 2. 准备 RPC 请求 rpcReq := &category.CreateCategoryRequest{ SystemId: req.SystemID, Name: req.Name, Description: req.Description, } // 可选参数处理 if req.Alias != "" { rpcReq.Alias = req.Alias } if req.ParentID != "" { rpcReq.ParentId = req.ParentID } // 3. 调用 RPC 服务 rpcResp, rpcErr := l.svcCtx.CategoryRpc.CreateCategory(l.ctx, rpcReq) if rpcErr != nil { return nil, rpcErr } // 4. 构建响应 resp = &types.CreateCategoryResp{ ID: rpcResp.Category.Id, } l.Logger.Infof("Category created successfully: ID=%s, Name=%s", resp.ID, req.Name) return resp, nil } // validateCreateRequest 验证创建分类请求 func validateCreateRequest(req *types.CreateCategoryReq) error { // 必需字段检查 if strings.TrimSpace(req.SystemID) == "" { return status.Error(codes.InvalidArgument, "systemId不能为空") } if strings.TrimSpace(req.Name) == "" { return status.Error(codes.InvalidArgument, "name不能为空") } // 名称长度限制 if len(req.Name) > 50 { return status.Error(codes.InvalidArgument, "alias cannot exceed 50 characters") } // 别名格式验证 (只允许字母、数字、连字符和下划线) // if req.Alias != "" { // if len(req.Alias) > 50 { // return errors.New("alias cannot exceed 50 characters") // } // for _, ch := range req.Alias { // if !(ch >= 'a' && ch <= 'z') && // !(ch >= 'A' && ch <= 'Z') && // !(ch >= '0' && ch <= '9') && // ch != '-' && ch != '_' { // return errors.New("alias can only contain letters, numbers, hyphens and underscores") // } // } // } // 描述长度限制 if len(req.Description) > 500 { return status.Error(codes.InvalidArgument, "description cannot exceed 500 characters") } return nil }