Skip to content

通知模块 ​

通知模块(notification)提供站内通知的创建、查询、已读标记等能力。支持所有权校验(用户只能访问自己的通知)和管理员管理接口。

架构概览 ​

modules/notification/
├── domain/          # Notification 实体、DTO、Repository 接口
├── application/     # Service(通知 CRUD、已读标记、计数)+ 单元测试
├── infrastructure/  # GORM NotificationRepository 实现、AutoMigrate
└── interfaces/      # HTTP Handler、路由注册

数据模型 ​

Notification 实体 ​

字段类型说明
IDuint主键
TenantIDstring (UUID)租户 ID,索引
UserIDuint接收用户 ID,索引
Titlestring(256)通知标题
Contenttext通知内容
Typestring(32)通知类型,默认 info(可选 info、warning)
IsReadbool是否已读,默认 false

数据库表: notifications

API 接口 ​

所有接口需认证 + 多租户中间件。

管理接口(需 notification.manage 权限) ​

方法路径权限说明
POST/api/v1/notificationsnotification.manage创建通知
DELETE/api/v1/notifications/:idnotification.manage删除通知
GET/api/v1/notifications/user/:userIdnotification.manage查询指定用户的通知列表

用户接口(仅需认证) ​

方法路径说明
GET/api/v1/notifications/:id获取通知详情
PUT/api/v1/notifications/:id/read标记单条已读
PUT/api/v1/notifications/read-all全部标记已读
GET/api/v1/notifications/unread-count获取未读数量

请求/响应示例 ​

创建通知 ​

json
// POST /api/v1/notifications
// Request
{
  "user_id": 5,
  "title": "系统升级通知",
  "content": "系统将于今晚 22:00 进行维护升级",
  "type": "warning"
}

// Response 200
{
  "id": 1,
  "tenant_id": "uuid-xxx",
  "user_id": 5,
  "title": "系统升级通知",
  "content": "系统将于今晚 22:00 进行维护升级",
  "type": "warning",
  "is_read": false,
  "created_at": "2026-10-01T10:00:00Z"
}

用户通知列表 ​

json
// GET /api/v1/notifications/user/5?page=1&page_size=20
// Response 200
{
  "items": [...],
  "total": 15,
  "page": 1
}

未读计数 ​

json
// GET /api/v1/notifications/unread-count
// Response 200
{
  "count": 3
}

安全特性 ​

所有权校验 ​

  • Get:获取通知时校验 UserID == 当前用户,不匹配返回 403
  • MarkAsRead:标记已读时校验所有权,不匹配返回 403

分页限制 ​

  • page 默认 1,最小 1
  • page_size 默认 20,范围 1~100

单元测试 ​

模块包含 9 个单元测试(application/service_test.go),使用内存 mockRepo 覆盖:

  • 创建通知(含类型默认值验证)
  • 获取通知(含不存在场景)
  • 用户列表查询(含分页)
  • 标记单条/全部已读
  • 未读计数
  • 删除通知

依赖注入 ​

go
fx.Module("notification",
    fx.Provide(
        infrastructure.NewNotificationRepository,
        application.NewService,
        NewHandler,
    ),
)

Released under the Apache 2.0 License.