mingyang-admin-iot-app/rpc/internal/logic/user/list_users_logic.go

96 lines
2.4 KiB
Go

package user
import (
"context"
"github.com/saas-mingyang/mingyang-admin-common/utils/pointy"
"mingyang-admin-app-rpc/ent/predicate"
"mingyang-admin-app-rpc/ent/user"
"mingyang-admin-app-rpc/internal/util/dberrorhandler"
"mingyang-admin-app-rpc/internal/svc"
"mingyang-admin-app-rpc/types/app"
"github.com/zeromicro/go-zero/core/logx"
)
type ListUsersLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewListUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUsersLogic {
return &ListUsersLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// ListUsers 分页查询用户信息
func (l *ListUsersLogic) ListUsers(in *app.PageUserRequest) (*app.PageUserResponse, error) {
var predicates []predicate.User
if in.Email != nil {
predicates = append(predicates, user.EmailContains(*in.Email))
}
result, err := l.svcCtx.DB.User.Query().Where(predicates...).Page(l.ctx, in.Page, in.PageSize)
if err != nil {
return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
}
resp := &app.PageUserResponse{}
// 在循环前添加验证
if result == nil || result.List == nil {
return resp, nil
}
resp.Total = result.PageDetails.Total
for _, v := range result.List {
if v == nil {
continue // 跳过 nil 项
}
// 确保结构体本身不为 nil
userInfo := &app.UserInfo{
Id: &v.ID,
Username: &v.Username,
Email: &v.Email,
IsVerified: &v.IsVerified,
}
// 处理时间字段
if !v.CreatedAt.IsZero() {
userInfo.CreatedAt = pointy.GetPointer(v.CreatedAt.UnixMilli())
}
if !v.UpdatedAt.IsZero() {
userInfo.UpdatedAt = pointy.GetPointer(v.UpdatedAt.UnixMilli())
}
// 处理可能为 nil 的字段
userInfo.Mobile = v.Mobile
userInfo.Avatar = v.Avatar
userInfo.NickName = v.Nickname
// 处理枚举字段 - 使用类型断言确保安全
if v.Gender != "" {
if gender, ok := interface{}(v.Gender).(interface{ String() string }); ok {
genderStr := gender.String()
userInfo.Gender = &genderStr
}
}
if v.AccountStatus != "" {
if status, ok := interface{}(v.AccountStatus).(interface{ String() string }); ok {
statusStr := status.String()
userInfo.AccountStatus = &statusStr
}
}
// 处理生日
if v.Birthday != nil && !v.Birthday.IsZero() {
userInfo.BirthdayAt = pointy.GetPointer(v.Birthday.UnixMilli())
}
resp.Data = append(resp.Data, userInfo)
}
return resp, nil
}