Appearance
通知模块
通知模块(notification)提供站内通知的创建、查询、已读标记等能力。支持所有权校验(用户只能访问自己的通知)和管理员管理接口。
架构概览
modules/notification/
├── domain/ # Notification 实体、DTO、Repository 接口
├── application/ # Service(通知 CRUD、已读标记、计数)+ 单元测试
├── infrastructure/ # GORM NotificationRepository 实现、AutoMigrate
└── interfaces/ # HTTP Handler、路由注册数据模型
Notification 实体
| 字段 | 类型 | 说明 |
|---|---|---|
| ID | uint | 主键 |
| TenantID | string (UUID) | 租户 ID,索引 |
| UserID | uint | 接收用户 ID,索引 |
| Title | string(256) | 通知标题 |
| Content | text | 通知内容 |
| Type | string(32) | 通知类型,默认 info(可选 info、warning) |
| IsRead | bool | 是否已读,默认 false |
数据库表: notifications
API 接口
所有接口需认证 + 多租户中间件。
管理接口(需 notification.manage 权限)
| 方法 | 路径 | 权限 | 说明 |
|---|---|---|---|
| POST | /api/v1/notifications | notification.manage | 创建通知 |
| DELETE | /api/v1/notifications/:id | notification.manage | 删除通知 |
| GET | /api/v1/notifications/user/:userId | notification.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 == 当前用户,不匹配返回 403MarkAsRead:标记已读时校验所有权,不匹配返回 403
分页限制
page默认 1,最小 1page_size默认 20,范围 1~100
单元测试
模块包含 9 个单元测试(application/service_test.go),使用内存 mockRepo 覆盖:
- 创建通知(含类型默认值验证)
- 获取通知(含不存在场景)
- 用户列表查询(含分页)
- 标记单条/全部已读
- 未读计数
- 删除通知
依赖注入
go
fx.Module("notification",
fx.Provide(
infrastructure.NewNotificationRepository,
application.NewService,
NewHandler,
),
)
