refactor: align framework cleanup with new bootstrap flow
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
50
internal/bootstrap/bootstrap.go
Normal file
50
internal/bootstrap/bootstrap.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
pkgGorm "github.com/break/junhong_cmp_fiber/pkg/gorm"
|
||||
)
|
||||
|
||||
// Bootstrap 初始化所有业务组件并返回 Handlers
|
||||
// 这是应用启动时的主入口,负责编排所有组件的初始化流程
|
||||
//
|
||||
// 初始化顺序:
|
||||
// 1. 初始化 Store 层(数据访问)
|
||||
// 2. 注册 GORM Callbacks(数据权限过滤等)- 需要 AccountStore
|
||||
// 3. 初始化 Service 层(业务逻辑)
|
||||
// 4. 初始化 Handler 层(HTTP 处理)
|
||||
//
|
||||
// 参数:
|
||||
// - deps: 基础依赖(DB, Redis, Logger)
|
||||
//
|
||||
// 返回:
|
||||
// - *Handlers: 所有 HTTP 处理器
|
||||
// - error: 初始化错误
|
||||
func Bootstrap(deps *Dependencies) (*Handlers, error) {
|
||||
// 1. 初始化 Store 层
|
||||
stores := initStores(deps)
|
||||
|
||||
// 2. 注册 GORM Callbacks(需要 AccountStore 来查询下级 ID)
|
||||
if err := registerGORMCallbacks(deps, stores); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 3. 初始化 Service 层
|
||||
services := initServices(stores)
|
||||
|
||||
// 4. 初始化 Handler 层
|
||||
handlers := initHandlers(services)
|
||||
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
// registerGORMCallbacks 注册 GORM Callbacks
|
||||
func registerGORMCallbacks(deps *Dependencies, stores *stores) error {
|
||||
// 注册数据权限过滤 Callback
|
||||
if err := pkgGorm.RegisterDataPermissionCallback(deps.DB, stores.Account); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// TODO: 在此添加其他 GORM Callbacks
|
||||
|
||||
return nil
|
||||
}
|
||||
15
internal/bootstrap/dependencies.go
Normal file
15
internal/bootstrap/dependencies.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Dependencies 封装所有基础依赖
|
||||
// 这些是应用启动时初始化的核心组件
|
||||
type Dependencies struct {
|
||||
DB *gorm.DB // PostgreSQL 数据库连接
|
||||
Redis *redis.Client // Redis 客户端
|
||||
Logger *zap.Logger // 应用日志器
|
||||
}
|
||||
15
internal/bootstrap/handlers.go
Normal file
15
internal/bootstrap/handlers.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
)
|
||||
|
||||
// initHandlers 初始化所有 Handler 实例
|
||||
func initHandlers(svc *services) *Handlers {
|
||||
return &Handlers{
|
||||
Account: handler.NewAccountHandler(svc.Account),
|
||||
Role: handler.NewRoleHandler(svc.Role),
|
||||
Permission: handler.NewPermissionHandler(svc.Permission),
|
||||
// TODO: 新增 Handler 在此初始化
|
||||
}
|
||||
}
|
||||
26
internal/bootstrap/services.go
Normal file
26
internal/bootstrap/services.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
accountSvc "github.com/break/junhong_cmp_fiber/internal/service/account"
|
||||
permissionSvc "github.com/break/junhong_cmp_fiber/internal/service/permission"
|
||||
roleSvc "github.com/break/junhong_cmp_fiber/internal/service/role"
|
||||
)
|
||||
|
||||
// services 封装所有 Service 实例
|
||||
// 注意:此结构体不导出,仅在 bootstrap 包内部使用
|
||||
type services struct {
|
||||
Account *accountSvc.Service
|
||||
Role *roleSvc.Service
|
||||
Permission *permissionSvc.Service
|
||||
// TODO: 新增 Service 在此添加字段
|
||||
}
|
||||
|
||||
// initServices 初始化所有 Service 实例
|
||||
func initServices(s *stores) *services {
|
||||
return &services{
|
||||
Account: accountSvc.New(s.Account, s.Role, s.AccountRole),
|
||||
Role: roleSvc.New(s.Role, s.Permission, s.RolePermission),
|
||||
Permission: permissionSvc.New(s.Permission),
|
||||
// TODO: 新增 Service 在此初始化
|
||||
}
|
||||
}
|
||||
28
internal/bootstrap/stores.go
Normal file
28
internal/bootstrap/stores.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
)
|
||||
|
||||
// stores 封装所有 Store 实例
|
||||
// 注意:此结构体不导出,仅在 bootstrap 包内部使用
|
||||
type stores struct {
|
||||
Account *postgres.AccountStore
|
||||
Role *postgres.RoleStore
|
||||
Permission *postgres.PermissionStore
|
||||
AccountRole *postgres.AccountRoleStore
|
||||
RolePermission *postgres.RolePermissionStore
|
||||
// TODO: 新增 Store 在此添加字段
|
||||
}
|
||||
|
||||
// initStores 初始化所有 Store 实例
|
||||
func initStores(deps *Dependencies) *stores {
|
||||
return &stores{
|
||||
Account: postgres.NewAccountStore(deps.DB, deps.Redis),
|
||||
Role: postgres.NewRoleStore(deps.DB),
|
||||
Permission: postgres.NewPermissionStore(deps.DB),
|
||||
AccountRole: postgres.NewAccountRoleStore(deps.DB),
|
||||
RolePermission: postgres.NewRolePermissionStore(deps.DB),
|
||||
// TODO: 新增 Store 在此初始化
|
||||
}
|
||||
}
|
||||
14
internal/bootstrap/types.go
Normal file
14
internal/bootstrap/types.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
)
|
||||
|
||||
// Handlers 封装所有 HTTP 处理器
|
||||
// 用于路由注册
|
||||
type Handlers struct {
|
||||
Account *handler.AccountHandler
|
||||
Role *handler.RoleHandler
|
||||
Permission *handler.PermissionHandler
|
||||
// TODO: 新增 Handler 在此添加字段
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/service/order"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// OrderHandler 订单处理器
|
||||
type OrderHandler struct {
|
||||
orderService *order.Service
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewOrderHandler 创建订单处理器实例
|
||||
func NewOrderHandler(orderService *order.Service, logger *zap.Logger) *OrderHandler {
|
||||
return &OrderHandler{
|
||||
orderService: orderService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateOrder 创建订单
|
||||
// POST /api/v1/orders
|
||||
func (h *OrderHandler) CreateOrder(c *fiber.Ctx) error {
|
||||
var req model.CreateOrderRequest
|
||||
|
||||
// 解析请求体
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析请求体失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
h.logger.Warn("参数验证失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Any("request", req),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
}
|
||||
|
||||
// 调用服务层创建订单
|
||||
orderResp, err := h.orderService.CreateOrder(c.Context(), &req)
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("创建订单失败",
|
||||
zap.String("order_id", req.OrderID),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "创建订单失败")
|
||||
}
|
||||
|
||||
h.logger.Info("订单创建成功",
|
||||
zap.Uint("order_id", orderResp.ID),
|
||||
zap.String("order_no", orderResp.OrderID))
|
||||
|
||||
return response.Success(c, orderResp)
|
||||
}
|
||||
|
||||
// GetOrder 获取订单详情
|
||||
// GET /api/v1/orders/:id
|
||||
func (h *OrderHandler) GetOrder(c *fiber.Ctx) error {
|
||||
// 获取路径参数
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
h.logger.Warn("订单ID格式错误",
|
||||
zap.String("id", idStr),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "订单ID格式错误")
|
||||
}
|
||||
|
||||
// 调用服务层获取订单
|
||||
orderResp, err := h.orderService.GetOrderByID(c.Context(), uint(id))
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("获取订单失败",
|
||||
zap.Uint("order_id", uint(id)),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "获取订单失败")
|
||||
}
|
||||
|
||||
return response.Success(c, orderResp)
|
||||
}
|
||||
|
||||
// UpdateOrder 更新订单信息
|
||||
// PUT /api/v1/orders/:id
|
||||
func (h *OrderHandler) UpdateOrder(c *fiber.Ctx) error {
|
||||
// 获取路径参数
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
h.logger.Warn("订单ID格式错误",
|
||||
zap.String("id", idStr),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "订单ID格式错误")
|
||||
}
|
||||
|
||||
var req model.UpdateOrderRequest
|
||||
|
||||
// 解析请求体
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析请求体失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
h.logger.Warn("参数验证失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Any("request", req),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
}
|
||||
|
||||
// 调用服务层更新订单
|
||||
orderResp, err := h.orderService.UpdateOrder(c.Context(), uint(id), &req)
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("更新订单失败",
|
||||
zap.Uint("order_id", uint(id)),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "更新订单失败")
|
||||
}
|
||||
|
||||
h.logger.Info("订单更新成功",
|
||||
zap.Uint("order_id", uint(id)))
|
||||
|
||||
return response.Success(c, orderResp)
|
||||
}
|
||||
|
||||
// ListOrders 获取订单列表(分页)
|
||||
// GET /api/v1/orders
|
||||
func (h *OrderHandler) ListOrders(c *fiber.Ctx) error {
|
||||
// 获取查询参数
|
||||
page, err := strconv.Atoi(c.Query("page", "1"))
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
pageSize, err := strconv.Atoi(c.Query("page_size", "20"))
|
||||
if err != nil || pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100 // 限制最大页大小
|
||||
}
|
||||
|
||||
// 可选的用户ID过滤
|
||||
var userID uint
|
||||
if userIDStr := c.Query("user_id"); userIDStr != "" {
|
||||
if id, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
|
||||
userID = uint(id)
|
||||
}
|
||||
}
|
||||
|
||||
// 调用服务层获取订单列表
|
||||
var orders []model.Order
|
||||
var total int64
|
||||
|
||||
if userID > 0 {
|
||||
// 按用户ID查询
|
||||
orders, total, err = h.orderService.ListOrdersByUserID(c.Context(), userID, page, pageSize)
|
||||
} else {
|
||||
// 查询所有订单
|
||||
orders, total, err = h.orderService.ListOrders(c.Context(), page, pageSize)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
return response.Error(c, fiber.StatusInternalServerError, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("获取订单列表失败",
|
||||
zap.Int("page", page),
|
||||
zap.Int("page_size", pageSize),
|
||||
zap.Uint("user_id", userID),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "获取订单列表失败")
|
||||
}
|
||||
|
||||
// 构造响应
|
||||
totalPages := int(total) / pageSize
|
||||
if int(total)%pageSize > 0 {
|
||||
totalPages++
|
||||
}
|
||||
|
||||
listResp := model.ListOrdersResponse{
|
||||
Orders: make([]model.OrderResponse, 0, len(orders)),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
Total: total,
|
||||
TotalPages: totalPages,
|
||||
}
|
||||
|
||||
// 转换为响应格式
|
||||
for _, o := range orders {
|
||||
listResp.Orders = append(listResp.Orders, model.OrderResponse{
|
||||
ID: o.ID,
|
||||
OrderID: o.OrderID,
|
||||
UserID: o.UserID,
|
||||
Amount: o.Amount,
|
||||
Status: o.Status,
|
||||
Remark: o.Remark,
|
||||
PaidAt: o.PaidAt,
|
||||
CompletedAt: o.CompletedAt,
|
||||
CreatedAt: o.CreatedAt,
|
||||
UpdatedAt: o.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
return response.Success(c, listResp)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
type TaskHandler struct {
|
||||
queueClient *queue.Client
|
||||
logger *zap.Logger
|
||||
validator *validator.Validate
|
||||
}
|
||||
|
||||
// NewTaskHandler 创建任务处理器实例
|
||||
@@ -27,6 +29,7 @@ func NewTaskHandler(queueClient *queue.Client, logger *zap.Logger) *TaskHandler
|
||||
return &TaskHandler{
|
||||
queueClient: queueClient,
|
||||
logger: logger,
|
||||
validator: validator.New(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,14 +75,14 @@ func (h *TaskHandler) SubmitEmailTask(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析邮件任务请求失败",
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
if err := h.validator.Struct(&req); err != nil {
|
||||
h.logger.Warn("邮件任务参数验证失败",
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
return errors.New(errors.CodeInvalidParam, err.Error())
|
||||
}
|
||||
|
||||
// 生成 RequestID(如果未提供)
|
||||
@@ -111,7 +114,7 @@ func (h *TaskHandler) SubmitEmailTask(c *fiber.Ctx) error {
|
||||
zap.String("to", req.To),
|
||||
zap.String("request_id", req.RequestID),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "任务提交失败")
|
||||
return errors.New(errors.CodeInternalError, "任务提交失败")
|
||||
}
|
||||
|
||||
h.logger.Info("邮件任务提交成功",
|
||||
@@ -141,14 +144,14 @@ func (h *TaskHandler) SubmitSyncTask(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析同步任务请求失败",
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
if err := h.validator.Struct(&req); err != nil {
|
||||
h.logger.Warn("同步任务参数验证失败",
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
return errors.New(errors.CodeInvalidParam, err.Error())
|
||||
}
|
||||
|
||||
// 生成 RequestID(如果未提供)
|
||||
@@ -192,7 +195,7 @@ func (h *TaskHandler) SubmitSyncTask(c *fiber.Ctx) error {
|
||||
zap.String("sync_type", req.SyncType),
|
||||
zap.String("request_id", req.RequestID),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "任务提交失败")
|
||||
return errors.New(errors.CodeInternalError, "任务提交失败")
|
||||
}
|
||||
|
||||
h.logger.Info("同步任务提交成功",
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/service/user"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var validate = validator.New()
|
||||
|
||||
// UserHandler 用户处理器
|
||||
type UserHandler struct {
|
||||
userService *user.Service
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewUserHandler 创建用户处理器实例
|
||||
func NewUserHandler(userService *user.Service, logger *zap.Logger) *UserHandler {
|
||||
return &UserHandler{
|
||||
userService: userService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser 创建用户
|
||||
// POST /api/v1/users
|
||||
func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
|
||||
var req model.CreateUserRequest
|
||||
|
||||
// 解析请求体
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析请求体失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
h.logger.Warn("参数验证失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Any("request", req),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
}
|
||||
|
||||
// 调用服务层创建用户
|
||||
userResp, err := h.userService.CreateUser(c.Context(), &req)
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
return response.Error(c, fiber.StatusInternalServerError, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("创建用户失败",
|
||||
zap.String("username", req.Username),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "创建用户失败")
|
||||
}
|
||||
|
||||
h.logger.Info("用户创建成功",
|
||||
zap.Uint("user_id", userResp.ID),
|
||||
zap.String("username", userResp.Username))
|
||||
|
||||
return response.Success(c, userResp)
|
||||
}
|
||||
|
||||
// GetUser 获取用户详情
|
||||
// GET /api/v1/users/:id
|
||||
func (h *UserHandler) GetUser(c *fiber.Ctx) error {
|
||||
// 获取路径参数
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
h.logger.Warn("用户ID格式错误",
|
||||
zap.String("id", idStr),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "用户ID格式错误")
|
||||
}
|
||||
|
||||
// 调用服务层获取用户
|
||||
userResp, err := h.userService.GetUserByID(c.Context(), uint(id))
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("获取用户失败",
|
||||
zap.Uint("user_id", uint(id)),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "获取用户失败")
|
||||
}
|
||||
|
||||
return response.Success(c, userResp)
|
||||
}
|
||||
|
||||
// UpdateUser 更新用户信息
|
||||
// PUT /api/v1/users/:id
|
||||
func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
|
||||
// 获取路径参数
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
h.logger.Warn("用户ID格式错误",
|
||||
zap.String("id", idStr),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "用户ID格式错误")
|
||||
}
|
||||
|
||||
var req model.UpdateUserRequest
|
||||
|
||||
// 解析请求体
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
h.logger.Warn("解析请求体失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "请求参数格式错误")
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if err := validate.Struct(&req); err != nil {
|
||||
h.logger.Warn("参数验证失败",
|
||||
zap.String("path", c.Path()),
|
||||
zap.Any("request", req),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, err.Error())
|
||||
}
|
||||
|
||||
// 调用服务层更新用户
|
||||
userResp, err := h.userService.UpdateUser(c.Context(), uint(id), &req)
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("更新用户失败",
|
||||
zap.Uint("user_id", uint(id)),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "更新用户失败")
|
||||
}
|
||||
|
||||
h.logger.Info("用户更新成功",
|
||||
zap.Uint("user_id", uint(id)))
|
||||
|
||||
return response.Success(c, userResp)
|
||||
}
|
||||
|
||||
// DeleteUser 删除用户(软删除)
|
||||
// DELETE /api/v1/users/:id
|
||||
func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
|
||||
// 获取路径参数
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
h.logger.Warn("用户ID格式错误",
|
||||
zap.String("id", idStr),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusBadRequest, errors.CodeBadRequest, "用户ID格式错误")
|
||||
}
|
||||
|
||||
// 调用服务层删除用户
|
||||
if err := h.userService.DeleteUser(c.Context(), uint(id)); err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
httpStatus := fiber.StatusInternalServerError
|
||||
if e.Code == errors.CodeNotFound {
|
||||
httpStatus = fiber.StatusNotFound
|
||||
}
|
||||
return response.Error(c, httpStatus, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("删除用户失败",
|
||||
zap.Uint("user_id", uint(id)),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "删除用户失败")
|
||||
}
|
||||
|
||||
h.logger.Info("用户删除成功",
|
||||
zap.Uint("user_id", uint(id)))
|
||||
|
||||
return response.Success(c, nil)
|
||||
}
|
||||
|
||||
// ListUsers 获取用户列表(分页)
|
||||
// GET /api/v1/users
|
||||
func (h *UserHandler) ListUsers(c *fiber.Ctx) error {
|
||||
// 获取查询参数
|
||||
page, err := strconv.Atoi(c.Query("page", "1"))
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
pageSize, err := strconv.Atoi(c.Query("page_size", "20"))
|
||||
if err != nil || pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100 // 限制最大页大小
|
||||
}
|
||||
|
||||
// 调用服务层获取用户列表
|
||||
users, total, err := h.userService.ListUsers(c.Context(), page, pageSize)
|
||||
if err != nil {
|
||||
if e, ok := err.(*errors.AppError); ok {
|
||||
return response.Error(c, fiber.StatusInternalServerError, e.Code, e.Message)
|
||||
}
|
||||
h.logger.Error("获取用户列表失败",
|
||||
zap.Int("page", page),
|
||||
zap.Int("page_size", pageSize),
|
||||
zap.Error(err))
|
||||
return response.Error(c, fiber.StatusInternalServerError, errors.CodeInternalError, "获取用户列表失败")
|
||||
}
|
||||
|
||||
// 构造响应
|
||||
totalPages := int(total) / pageSize
|
||||
if int(total)%pageSize > 0 {
|
||||
totalPages++
|
||||
}
|
||||
|
||||
listResp := model.ListUsersResponse{
|
||||
Users: make([]model.UserResponse, 0, len(users)),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
Total: total,
|
||||
TotalPages: totalPages,
|
||||
}
|
||||
|
||||
// 转换为响应格式
|
||||
for _, u := range users {
|
||||
listResp.Users = append(listResp.Users, model.UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
Email: u.Email,
|
||||
Status: u.Status,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
LastLoginAt: u.LastLoginAt,
|
||||
})
|
||||
}
|
||||
|
||||
return response.Success(c, listResp)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/keyauth"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/validator"
|
||||
)
|
||||
|
||||
// KeyAuth 创建基于 Redis 的令牌认证中间件
|
||||
func KeyAuth(v *validator.TokenValidator, logger *zap.Logger) fiber.Handler {
|
||||
return keyauth.New(keyauth.Config{
|
||||
KeyLookup: "header:token",
|
||||
Validator: func(c *fiber.Ctx, key string) (bool, error) {
|
||||
// 验证令牌
|
||||
userID, err := v.Validate(key)
|
||||
if err != nil {
|
||||
// 获取请求 ID 用于日志
|
||||
requestID := ""
|
||||
if rid := c.Locals(constants.ContextKeyRequestID); rid != nil {
|
||||
requestID = rid.(string)
|
||||
}
|
||||
|
||||
logger.Warn("令牌验证失败",
|
||||
zap.String("request_id", requestID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 在上下文中存储用户 ID
|
||||
c.Locals(constants.ContextKeyUserID, userID)
|
||||
return true, nil
|
||||
},
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
// 将错误映射到统一响应格式
|
||||
switch err {
|
||||
case keyauth.ErrMissingOrMalformedAPIKey:
|
||||
return response.Error(c, 400, errors.CodeMissingToken, errors.GetMessage(errors.CodeMissingToken, "zh"))
|
||||
case errors.ErrInvalidToken:
|
||||
return response.Error(c, 400, errors.CodeInvalidToken, errors.GetMessage(errors.CodeInvalidToken, "zh"))
|
||||
case errors.ErrRedisUnavailable:
|
||||
return response.Error(c, 503, errors.CodeAuthServiceUnavailable, errors.GetMessage(errors.CodeAuthServiceUnavailable, "zh"))
|
||||
default:
|
||||
return response.Error(c, 500, errors.CodeInternalError, errors.GetMessage(errors.CodeInternalError, "zh"))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// RateLimiter 创建基于 IP 的限流中间件
|
||||
@@ -23,7 +22,7 @@ func RateLimiter(max int, expiration time.Duration, storage fiber.Storage) fiber
|
||||
return constants.RedisRateLimitKey(c.IP())
|
||||
},
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
return response.Error(c, 429, errors.CodeTooManyRequests, errors.GetMessage(errors.CodeTooManyRequests, "zh"))
|
||||
return errors.New(errors.CodeTooManyRequests, errors.GetMessage(errors.CodeTooManyRequests, "zh"))
|
||||
},
|
||||
Storage: storage, // 支持内存或 Redis 存储
|
||||
})
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Order 订单实体
|
||||
type Order struct {
|
||||
BaseModel
|
||||
|
||||
// 业务唯一键
|
||||
OrderID string `gorm:"uniqueIndex:uk_order_order_id;not null;size:50" json:"order_id"`
|
||||
|
||||
// 关联关系 (仅存储 ID,不使用 GORM 关联)
|
||||
UserID uint `gorm:"not null;index:idx_order_user_id" json:"user_id"`
|
||||
|
||||
// 订单信息
|
||||
Amount int64 `gorm:"not null" json:"amount"` // 金额(分)
|
||||
Status string `gorm:"not null;size:20;default:'pending';index:idx_order_status" json:"status"`
|
||||
Remark string `gorm:"size:500" json:"remark,omitempty"`
|
||||
|
||||
// 时间字段
|
||||
PaidAt *time.Time `gorm:"column:paid_at" json:"paid_at,omitempty"`
|
||||
CompletedAt *time.Time `gorm:"column:completed_at" json:"completed_at,omitempty"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (Order) TableName() string {
|
||||
return "tb_order"
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// CreateOrderRequest 创建订单请求
|
||||
type CreateOrderRequest struct {
|
||||
OrderID string `json:"order_id" validate:"required,min=10,max=50"`
|
||||
UserID uint `json:"user_id" validate:"required,gt=0"`
|
||||
Amount int64 `json:"amount" validate:"required,gte=0"`
|
||||
Remark string `json:"remark" validate:"omitempty,max=500"`
|
||||
}
|
||||
|
||||
// UpdateOrderRequest 更新订单请求
|
||||
type UpdateOrderRequest struct {
|
||||
Status *string `json:"status" validate:"omitempty,oneof=pending paid processing completed cancelled"`
|
||||
Remark *string `json:"remark" validate:"omitempty,max=500"`
|
||||
}
|
||||
|
||||
// OrderResponse 订单响应
|
||||
type OrderResponse struct {
|
||||
ID uint `json:"id"`
|
||||
OrderID string `json:"order_id"`
|
||||
UserID uint `json:"user_id"`
|
||||
Amount int64 `json:"amount"`
|
||||
Status string `json:"status"`
|
||||
Remark string `json:"remark,omitempty"`
|
||||
PaidAt *time.Time `json:"paid_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
User *UserResponse `json:"user,omitempty"` // 可选的用户信息
|
||||
}
|
||||
|
||||
// ListOrdersResponse 订单列表响应
|
||||
type ListOrdersResponse struct {
|
||||
Orders []OrderResponse `json:"orders"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// User 用户实体
|
||||
type User struct {
|
||||
BaseModel
|
||||
|
||||
// 基本信息
|
||||
Username string `gorm:"uniqueIndex:uk_user_username;not null;size:50" json:"username"`
|
||||
Email string `gorm:"uniqueIndex:uk_user_email;not null;size:100" json:"email"`
|
||||
Password string `gorm:"not null;size:255" json:"-"` // 不返回给客户端
|
||||
|
||||
// 状态字段
|
||||
Status string `gorm:"not null;size:20;default:'active';index:idx_user_status" json:"status"`
|
||||
|
||||
// 元数据
|
||||
LastLoginAt *time.Time `gorm:"column:last_login_at" json:"last_login_at,omitempty"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (User) TableName() string {
|
||||
return "tb_user"
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// CreateUserRequest 创建用户请求
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" validate:"required,min=3,max=50,alphanum"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password" validate:"required,min=8"`
|
||||
}
|
||||
|
||||
// UpdateUserRequest 更新用户请求
|
||||
type UpdateUserRequest struct {
|
||||
Email *string `json:"email" validate:"omitempty,email"`
|
||||
Status *string `json:"status" validate:"omitempty,oneof=active inactive suspended"`
|
||||
}
|
||||
|
||||
// UserResponse 用户响应
|
||||
type UserResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
|
||||
}
|
||||
|
||||
// ListUsersResponse 用户列表响应
|
||||
type ListUsersResponse struct {
|
||||
Users []UserResponse `json:"users"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
@@ -3,21 +3,12 @@ package routes
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
"github.com/break/junhong_cmp_fiber/internal/bootstrap"
|
||||
)
|
||||
|
||||
// Services 容器,包含所有业务 Handler
|
||||
// 由 main 函数初始化并传递给路由注册函数
|
||||
type Services struct {
|
||||
// RBAC 相关 Handler
|
||||
AccountHandler *handler.AccountHandler
|
||||
RoleHandler *handler.RoleHandler
|
||||
PermissionHandler *handler.PermissionHandler
|
||||
}
|
||||
|
||||
// RegisterRoutes 路由注册总入口
|
||||
// 按业务模块调用各自的路由注册函数
|
||||
func RegisterRoutes(app *fiber.App, services *Services) {
|
||||
func RegisterRoutes(app *fiber.App, handlers *bootstrap.Handlers) {
|
||||
// API 路由组
|
||||
api := app.Group("/api/v1")
|
||||
|
||||
@@ -26,13 +17,13 @@ func RegisterRoutes(app *fiber.App, services *Services) {
|
||||
registerTaskRoutes(api)
|
||||
|
||||
// RBAC 路由
|
||||
if services.AccountHandler != nil {
|
||||
registerAccountRoutes(api, services.AccountHandler)
|
||||
if handlers.Account != nil {
|
||||
registerAccountRoutes(api, handlers.Account)
|
||||
}
|
||||
if services.RoleHandler != nil {
|
||||
registerRoleRoutes(api, services.RoleHandler)
|
||||
if handlers.Role != nil {
|
||||
registerRoleRoutes(api, handlers.Role)
|
||||
}
|
||||
if services.PermissionHandler != nil {
|
||||
registerPermissionRoutes(api, services.PermissionHandler)
|
||||
if handlers.Permission != nil {
|
||||
registerPermissionRoutes(api, handlers.Permission)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
pkgErrors "github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service 订单服务
|
||||
type Service struct {
|
||||
store *postgres.Store
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewService 创建订单服务
|
||||
func NewService(store *postgres.Store, logger *zap.Logger) *Service {
|
||||
return &Service{
|
||||
store: store,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateOrder 创建订单
|
||||
func (s *Service) CreateOrder(ctx context.Context, req *model.CreateOrderRequest) (*model.Order, error) {
|
||||
// 验证用户是否存在
|
||||
_, err := s.store.User.GetByID(ctx, req.UserID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, pkgErrors.New(pkgErrors.CodeNotFound, "用户不存在")
|
||||
}
|
||||
s.logger.Error("查询用户失败",
|
||||
zap.Uint("user_id", req.UserID),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "查询用户失败")
|
||||
}
|
||||
|
||||
// 创建订单
|
||||
order := &model.Order{
|
||||
OrderID: req.OrderID,
|
||||
UserID: req.UserID,
|
||||
Amount: req.Amount,
|
||||
Status: constants.OrderStatusPending,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
|
||||
if err := s.store.Order.Create(ctx, order); err != nil {
|
||||
s.logger.Error("创建订单失败",
|
||||
zap.String("order_id", req.OrderID),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "创建订单失败")
|
||||
}
|
||||
|
||||
s.logger.Info("订单创建成功",
|
||||
zap.Uint("id", order.ID),
|
||||
zap.String("order_id", order.OrderID),
|
||||
zap.Uint("user_id", order.UserID))
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// GetOrderByID 根据 ID 获取订单
|
||||
func (s *Service) GetOrderByID(ctx context.Context, id uint) (*model.Order, error) {
|
||||
order, err := s.store.Order.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, pkgErrors.New(pkgErrors.CodeNotFound, "订单不存在")
|
||||
}
|
||||
s.logger.Error("获取订单失败",
|
||||
zap.Uint("order_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "获取订单失败")
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// UpdateOrder 更新订单
|
||||
func (s *Service) UpdateOrder(ctx context.Context, id uint, req *model.UpdateOrderRequest) (*model.Order, error) {
|
||||
// 查询订单
|
||||
order, err := s.store.Order.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, pkgErrors.New(pkgErrors.CodeNotFound, "订单不存在")
|
||||
}
|
||||
s.logger.Error("查询订单失败",
|
||||
zap.Uint("order_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "查询订单失败")
|
||||
}
|
||||
|
||||
// 更新字段
|
||||
if req.Status != nil {
|
||||
order.Status = *req.Status
|
||||
// 根据状态自动设置时间字段
|
||||
now := time.Now()
|
||||
switch *req.Status {
|
||||
case constants.OrderStatusPaid:
|
||||
order.PaidAt = &now
|
||||
case constants.OrderStatusCompleted:
|
||||
order.CompletedAt = &now
|
||||
}
|
||||
}
|
||||
if req.Remark != nil {
|
||||
order.Remark = *req.Remark
|
||||
}
|
||||
|
||||
// 保存更新
|
||||
if err := s.store.Order.Update(ctx, order); err != nil {
|
||||
s.logger.Error("更新订单失败",
|
||||
zap.Uint("order_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "更新订单失败")
|
||||
}
|
||||
|
||||
s.logger.Info("订单更新成功",
|
||||
zap.Uint("id", order.ID),
|
||||
zap.String("order_id", order.OrderID))
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// DeleteOrder 删除订单(软删除)
|
||||
func (s *Service) DeleteOrder(ctx context.Context, id uint) error {
|
||||
// 检查订单是否存在
|
||||
_, err := s.store.Order.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return pkgErrors.New(pkgErrors.CodeNotFound, "订单不存在")
|
||||
}
|
||||
s.logger.Error("查询订单失败",
|
||||
zap.Uint("order_id", id),
|
||||
zap.Error(err))
|
||||
return pkgErrors.New(pkgErrors.CodeInternalError, "查询订单失败")
|
||||
}
|
||||
|
||||
// 软删除
|
||||
if err := s.store.Order.Delete(ctx, id); err != nil {
|
||||
s.logger.Error("删除订单失败",
|
||||
zap.Uint("order_id", id),
|
||||
zap.Error(err))
|
||||
return pkgErrors.New(pkgErrors.CodeInternalError, "删除订单失败")
|
||||
}
|
||||
|
||||
s.logger.Info("订单删除成功", zap.Uint("order_id", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListOrders 分页获取订单列表
|
||||
func (s *Service) ListOrders(ctx context.Context, page, pageSize int) ([]model.Order, int64, error) {
|
||||
// 参数验证
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
if pageSize > constants.MaxPageSize {
|
||||
pageSize = constants.MaxPageSize
|
||||
}
|
||||
|
||||
orders, total, err := s.store.Order.List(ctx, page, pageSize)
|
||||
if err != nil {
|
||||
s.logger.Error("获取订单列表失败",
|
||||
zap.Int("page", page),
|
||||
zap.Int("page_size", pageSize),
|
||||
zap.Error(err))
|
||||
return nil, 0, pkgErrors.New(pkgErrors.CodeInternalError, "获取订单列表失败")
|
||||
}
|
||||
|
||||
return orders, total, nil
|
||||
}
|
||||
|
||||
// ListOrdersByUserID 根据用户ID分页获取订单列表
|
||||
func (s *Service) ListOrdersByUserID(ctx context.Context, userID uint, page, pageSize int) ([]model.Order, int64, error) {
|
||||
// 参数验证
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
if pageSize > constants.MaxPageSize {
|
||||
pageSize = constants.MaxPageSize
|
||||
}
|
||||
|
||||
orders, total, err := s.store.Order.ListByUserID(ctx, userID, page, pageSize)
|
||||
if err != nil {
|
||||
s.logger.Error("获取用户订单列表失败",
|
||||
zap.Uint("user_id", userID),
|
||||
zap.Int("page", page),
|
||||
zap.Int("page_size", pageSize),
|
||||
zap.Error(err))
|
||||
return nil, 0, pkgErrors.New(pkgErrors.CodeInternalError, "获取订单列表失败")
|
||||
}
|
||||
|
||||
return orders, total, nil
|
||||
}
|
||||
|
||||
// CreateOrderWithUser 创建订单并更新用户统计(事务示例)
|
||||
func (s *Service) CreateOrderWithUser(ctx context.Context, req *model.CreateOrderRequest) (*model.Order, error) {
|
||||
var order *model.Order
|
||||
|
||||
// 使用事务
|
||||
err := s.store.Transaction(ctx, func(tx *postgres.Store) error {
|
||||
// 1. 验证用户是否存在
|
||||
user, err := tx.User.GetByID(ctx, req.UserID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return pkgErrors.New(pkgErrors.CodeNotFound, "用户不存在")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 创建订单
|
||||
order = &model.Order{
|
||||
OrderID: req.OrderID,
|
||||
UserID: req.UserID,
|
||||
Amount: req.Amount,
|
||||
Status: constants.OrderStatusPending,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
|
||||
if err := tx.Order.Create(ctx, order); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 更新用户状态(示例:可以在这里更新用户的订单计数等)
|
||||
s.logger.Debug("订单创建成功,用户信息",
|
||||
zap.String("username", user.Username),
|
||||
zap.String("order_id", order.OrderID))
|
||||
|
||||
return nil // 提交事务
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.logger.Error("事务创建订单失败",
|
||||
zap.String("order_id", req.OrderID),
|
||||
zap.Error(err))
|
||||
return nil, fmt.Errorf("创建订单失败: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("事务创建订单成功",
|
||||
zap.Uint("id", order.ID),
|
||||
zap.String("order_id", order.OrderID),
|
||||
zap.Uint("user_id", order.UserID))
|
||||
|
||||
return order, nil
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
pkgErrors "github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service 用户服务
|
||||
type Service struct {
|
||||
store *postgres.Store
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewService 创建用户服务
|
||||
func NewService(store *postgres.Store, logger *zap.Logger) *Service {
|
||||
return &Service{
|
||||
store: store,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser 创建用户
|
||||
func (s *Service) CreateUser(ctx context.Context, req *model.CreateUserRequest) (*model.User, error) {
|
||||
// 密码哈希
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
s.logger.Error("密码哈希失败", zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "密码加密失败")
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
user := &model.User{
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
Password: string(hashedPassword),
|
||||
Status: constants.UserStatusActive,
|
||||
}
|
||||
|
||||
if err := s.store.User.Create(ctx, user); err != nil {
|
||||
s.logger.Error("创建用户失败",
|
||||
zap.String("username", req.Username),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "创建用户失败")
|
||||
}
|
||||
|
||||
s.logger.Info("用户创建成功",
|
||||
zap.Uint("user_id", user.ID),
|
||||
zap.String("username", user.Username))
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetUserByID 根据 ID 获取用户
|
||||
func (s *Service) GetUserByID(ctx context.Context, id uint) (*model.User, error) {
|
||||
user, err := s.store.User.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, pkgErrors.New(pkgErrors.CodeNotFound, "用户不存在")
|
||||
}
|
||||
s.logger.Error("获取用户失败",
|
||||
zap.Uint("user_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "获取用户失败")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateUser 更新用户
|
||||
func (s *Service) UpdateUser(ctx context.Context, id uint, req *model.UpdateUserRequest) (*model.User, error) {
|
||||
// 查询用户
|
||||
user, err := s.store.User.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, pkgErrors.New(pkgErrors.CodeNotFound, "用户不存在")
|
||||
}
|
||||
s.logger.Error("查询用户失败",
|
||||
zap.Uint("user_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "查询用户失败")
|
||||
}
|
||||
|
||||
// 更新字段
|
||||
if req.Email != nil {
|
||||
user.Email = *req.Email
|
||||
}
|
||||
if req.Status != nil {
|
||||
user.Status = *req.Status
|
||||
}
|
||||
|
||||
// 保存更新
|
||||
if err := s.store.User.Update(ctx, user); err != nil {
|
||||
s.logger.Error("更新用户失败",
|
||||
zap.Uint("user_id", id),
|
||||
zap.Error(err))
|
||||
return nil, pkgErrors.New(pkgErrors.CodeInternalError, "更新用户失败")
|
||||
}
|
||||
|
||||
s.logger.Info("用户更新成功",
|
||||
zap.Uint("user_id", user.ID),
|
||||
zap.String("username", user.Username))
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// DeleteUser 删除用户(软删除)
|
||||
func (s *Service) DeleteUser(ctx context.Context, id uint) error {
|
||||
// 检查用户是否存在
|
||||
_, err := s.store.User.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return pkgErrors.New(pkgErrors.CodeNotFound, "用户不存在")
|
||||
}
|
||||
s.logger.Error("查询用户失败",
|
||||
zap.Uint("user_id", id),
|
||||
zap.Error(err))
|
||||
return pkgErrors.New(pkgErrors.CodeInternalError, "查询用户失败")
|
||||
}
|
||||
|
||||
// 软删除
|
||||
if err := s.store.User.Delete(ctx, id); err != nil {
|
||||
s.logger.Error("删除用户失败",
|
||||
zap.Uint("user_id", id),
|
||||
zap.Error(err))
|
||||
return pkgErrors.New(pkgErrors.CodeInternalError, "删除用户失败")
|
||||
}
|
||||
|
||||
s.logger.Info("用户删除成功", zap.Uint("user_id", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUsers 分页获取用户列表
|
||||
func (s *Service) ListUsers(ctx context.Context, page, pageSize int) ([]model.User, int64, error) {
|
||||
// 参数验证
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = constants.DefaultPageSize
|
||||
}
|
||||
if pageSize > constants.MaxPageSize {
|
||||
pageSize = constants.MaxPageSize
|
||||
}
|
||||
|
||||
users, total, err := s.store.User.List(ctx, page, pageSize)
|
||||
if err != nil {
|
||||
s.logger.Error("获取用户列表失败",
|
||||
zap.Int("page", page),
|
||||
zap.Int("page_size", pageSize),
|
||||
zap.Error(err))
|
||||
return nil, 0, pkgErrors.New(pkgErrors.CodeInternalError, "获取用户列表失败")
|
||||
}
|
||||
|
||||
return users, total, nil
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OrderStore 订单数据访问层
|
||||
type OrderStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrderStore 创建订单 Store
|
||||
func NewOrderStore(db *gorm.DB) *OrderStore {
|
||||
return &OrderStore{db: db}
|
||||
}
|
||||
|
||||
// Create 创建订单
|
||||
func (s *OrderStore) Create(ctx context.Context, order *model.Order) error {
|
||||
return s.db.WithContext(ctx).Create(order).Error
|
||||
}
|
||||
|
||||
// GetByID 根据 ID 获取订单
|
||||
func (s *OrderStore) GetByID(ctx context.Context, id uint) (*model.Order, error) {
|
||||
var order model.Order
|
||||
err := s.db.WithContext(ctx).First(&order, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
// GetByOrderID 根据订单号获取订单
|
||||
func (s *OrderStore) GetByOrderID(ctx context.Context, orderID string) (*model.Order, error) {
|
||||
var order model.Order
|
||||
err := s.db.WithContext(ctx).Where("order_id = ?", orderID).First(&order).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
// ListByUserID 根据用户 ID 分页获取订单列表
|
||||
func (s *OrderStore) ListByUserID(ctx context.Context, userID uint, page, pageSize int) ([]model.Order, int64, error) {
|
||||
var orders []model.Order
|
||||
var total int64
|
||||
|
||||
// 计算总数
|
||||
if err := s.db.WithContext(ctx).Model(&model.Order{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("user_id = ?", userID).
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Order("created_at DESC").
|
||||
Find(&orders).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return orders, total, nil
|
||||
}
|
||||
|
||||
// List 分页获取订单列表(全部订单)
|
||||
func (s *OrderStore) List(ctx context.Context, page, pageSize int) ([]model.Order, int64, error) {
|
||||
var orders []model.Order
|
||||
var total int64
|
||||
|
||||
// 计算总数
|
||||
if err := s.db.WithContext(ctx).Model(&model.Order{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
err := s.db.WithContext(ctx).
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Order("created_at DESC").
|
||||
Find(&orders).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return orders, total, nil
|
||||
}
|
||||
|
||||
// Update 更新订单
|
||||
func (s *OrderStore) Update(ctx context.Context, order *model.Order) error {
|
||||
return s.db.WithContext(ctx).Save(order).Error
|
||||
}
|
||||
|
||||
// Delete 软删除订单
|
||||
func (s *OrderStore) Delete(ctx context.Context, id uint) error {
|
||||
return s.db.WithContext(ctx).Delete(&model.Order{}, id).Error
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/logger"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DataPermissionScope 数据权限过滤 Scope
|
||||
// 根据 context 中的用户信息自动过滤数据
|
||||
// - root 用户跳过过滤
|
||||
// - 普通用户只能查看自己和下级的数据
|
||||
// - 同时限制 shop_id 相同
|
||||
func DataPermissionScope(ctx context.Context, accountStore *AccountStore) func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
// 1. 检查是否为 root 用户,root 用户跳过数据权限过滤
|
||||
if middleware.IsRootUser(ctx) {
|
||||
return db
|
||||
}
|
||||
|
||||
// 2. 获取当前用户 ID
|
||||
userID := middleware.GetUserIDFromContext(ctx)
|
||||
if userID == 0 {
|
||||
// 未登录用户返回空结果
|
||||
logger.GetAppLogger().Warn("数据权限过滤:未获取到用户 ID")
|
||||
return db.Where("1 = 0")
|
||||
}
|
||||
|
||||
// 3. 获取当前用户的 shop_id
|
||||
shopID := middleware.GetShopIDFromContext(ctx)
|
||||
|
||||
// 4. 获取当前用户及所有下级的 ID
|
||||
subordinateIDs, err := accountStore.GetSubordinateIDs(ctx, userID)
|
||||
if err != nil {
|
||||
// 查询失败时,降级为只能看自己的数据
|
||||
|
||||
logger.GetAppLogger().Error("数据权限过滤:获取下级 ID 失败",
|
||||
zap.Uint("user_id", userID),
|
||||
zap.Error(err))
|
||||
subordinateIDs = []uint{userID}
|
||||
}
|
||||
|
||||
// 5. 应用数据权限过滤条件
|
||||
// owner_id IN (用户自己及所有下级) AND shop_id = 当前用户 shop_id
|
||||
if len(subordinateIDs) == 0 {
|
||||
subordinateIDs = []uint{userID}
|
||||
}
|
||||
|
||||
// 根据是否有 shop_id 过滤条件决定 SQL
|
||||
if shopID != 0 {
|
||||
return db.Where("owner_id IN ? AND shop_id = ?", subordinateIDs, shopID)
|
||||
}
|
||||
|
||||
// 如果 shop_id 为 0,只根据 owner_id 过滤
|
||||
return db.Where("owner_id IN ?", subordinateIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// WithoutDataPermission 跳过数据权限过滤的 Scope
|
||||
// 用于需要查询所有数据的场景(如管理后台统计、系统任务等)
|
||||
func WithoutDataPermission() func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
// 什么都不做,直接返回原 db
|
||||
return db
|
||||
}
|
||||
}
|
||||
|
||||
// SoftDeleteScope 软删除过滤 Scope(GORM 默认已支持,此处作为示例)
|
||||
// 只查询未软删除的记录
|
||||
func SoftDeleteScope() func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
return db.Where("deleted_at IS NULL")
|
||||
}
|
||||
}
|
||||
|
||||
// StatusEnabledScope 状态启用过滤 Scope
|
||||
// 只查询状态为启用的记录
|
||||
func StatusEnabledScope() func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
return db.Where("status = ?", constants.StatusEnabled)
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Store PostgreSQL 数据访问层整合结构
|
||||
type Store struct {
|
||||
db *gorm.DB
|
||||
logger *zap.Logger
|
||||
|
||||
User *UserStore
|
||||
Order *OrderStore
|
||||
}
|
||||
|
||||
// NewStore 创建新的 PostgreSQL Store 实例
|
||||
func NewStore(db *gorm.DB, logger *zap.Logger) *Store {
|
||||
return &Store{
|
||||
db: db,
|
||||
logger: logger,
|
||||
User: NewUserStore(db),
|
||||
Order: NewOrderStore(db),
|
||||
}
|
||||
}
|
||||
|
||||
// DB 获取数据库连接
|
||||
func (s *Store) DB() *gorm.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
// Transaction 执行事务
|
||||
// 提供统一的事务管理接口,自动处理提交和回滚
|
||||
// 在事务内部,所有 Store 操作都会使用事务连接
|
||||
func (s *Store) Transaction(ctx context.Context, fn func(*Store) error) error {
|
||||
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 创建事务内的 Store 实例
|
||||
txStore := &Store{
|
||||
db: tx,
|
||||
logger: s.logger,
|
||||
User: NewUserStore(tx),
|
||||
Order: NewOrderStore(tx),
|
||||
}
|
||||
return fn(txStore)
|
||||
})
|
||||
}
|
||||
|
||||
// WithContext 返回带上下文的数据库实例
|
||||
func (s *Store) WithContext(ctx context.Context) *gorm.DB {
|
||||
return s.db.WithContext(ctx)
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// UserStore 用户数据访问层
|
||||
type UserStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewUserStore 创建用户 Store
|
||||
func NewUserStore(db *gorm.DB) *UserStore {
|
||||
return &UserStore{db: db}
|
||||
}
|
||||
|
||||
// Create 创建用户
|
||||
func (s *UserStore) Create(ctx context.Context, user *model.User) error {
|
||||
return s.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
// GetByID 根据 ID 获取用户
|
||||
func (s *UserStore) GetByID(ctx context.Context, id uint) (*model.User, error) {
|
||||
var user model.User
|
||||
err := s.db.WithContext(ctx).First(&user, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetByUsername 根据用户名获取用户
|
||||
func (s *UserStore) GetByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
var user model.User
|
||||
err := s.db.WithContext(ctx).Where("username = ?", username).First(&user).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// List 分页获取用户列表
|
||||
func (s *UserStore) List(ctx context.Context, page, pageSize int) ([]model.User, int64, error) {
|
||||
var users []model.User
|
||||
var total int64
|
||||
|
||||
// 计算总数
|
||||
if err := s.db.WithContext(ctx).Model(&model.User{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 分页查询
|
||||
offset := (page - 1) * pageSize
|
||||
err := s.db.WithContext(ctx).
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Order("created_at DESC").
|
||||
Find(&users).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
// Update 更新用户
|
||||
func (s *UserStore) Update(ctx context.Context, user *model.User) error {
|
||||
return s.db.WithContext(ctx).Save(user).Error
|
||||
}
|
||||
|
||||
// Delete 软删除用户
|
||||
func (s *UserStore) Delete(ctx context.Context, id uint) error {
|
||||
return s.db.WithContext(ctx).Delete(&model.User{}, id).Error
|
||||
}
|
||||
Reference in New Issue
Block a user