86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
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 GetCategoryLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewGetCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCategoryLogic {
|
|
return &GetCategoryLogic{
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
Logger: logx.WithContext(ctx),
|
|
}
|
|
}
|
|
|
|
func (l *GetCategoryLogic) GetCategory(in *category.GetCategoryRequest) (*category.CategoryInfoResponse, error) {
|
|
// 1. 参数校验
|
|
if in.Id == "" {
|
|
return nil, status.Error(codes.InvalidArgument, "分类ID不能为空")
|
|
}
|
|
|
|
// 2. 查询数据库
|
|
categoryData, 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. 转换响应格式
|
|
return l.convertToResponse(categoryData), nil
|
|
}
|
|
|
|
func (l *GetCategoryLogic) convertToResponse(c *model.Categories) *category.CategoryInfoResponse {
|
|
// 处理可能为空的字段
|
|
var alias, parentID, description string
|
|
|
|
if c.Alias.Valid {
|
|
alias = c.Alias.String
|
|
}
|
|
if c.ParentId.Valid {
|
|
parentID = c.ParentId.String
|
|
}
|
|
if c.Description.Valid {
|
|
description = c.Description.String
|
|
}
|
|
|
|
// 处理时间戳
|
|
var updatedAt int64
|
|
if c.UpdatedAt.Valid {
|
|
updatedAt = c.UpdatedAt.Time.Unix()
|
|
} else {
|
|
updatedAt = c.CreatedAt.Unix() // 如果未更新过,使用创建时间
|
|
}
|
|
|
|
return &category.CategoryInfoResponse{
|
|
Category: &category.CategoryInfo{
|
|
Id: c.Id,
|
|
SystemId: c.SystemId,
|
|
Name: c.Name,
|
|
Alias: alias,
|
|
ParentId: parentID,
|
|
Description: description,
|
|
CreatedAt: c.CreatedAt.Unix(),
|
|
UpdatedAt: updatedAt,
|
|
},
|
|
}
|
|
}
|