3.6 KiB
3.6 KiB
通知系统 (Notice System)
功能概述
这是一个完整的通知系统,支持实时通知推送、定时通知、通知状态管理等功能。
主要特性
- ✅ 实时WebSocket通知推送
- ✅ 定时通知发送
- ✅ 通知状态管理(待发送、已发送、已读、失败)
- ✅ 支持单用户通知和广播通知
- ✅ 通知类型分类(系统、用户、广播)
- ✅ 未读通知计数
- ✅ RESTful API接口
API接口
1. 创建通知
POST /api/notices
2. 获取通知列表
GET /api/notices
GET /api/notices?all=true # 管理员获取所有通知
3. 获取未读通知数量
GET /api/notices/unread-count
4. 获取通知详情
GET /api/notices/:id
5. 标记通知为已读
PATCH /api/notices/:id/read
6. 发送系统通知
POST /api/notices/system
7. 发送广播通知
POST /api/notices/broadcast
WebSocket连接
连接地址
ws://localhost:3000/ws/notice
认证
连接后需要发送认证消息:
{
"event": "authenticate",
"data": { "userId": 123 }
}
接收通知
客户端会收到以下格式的通知:
{
"type": "notice",
"data": {
"id": 1,
"title": "通知标题",
"content": "通知内容",
"type": "system",
"status": "sent",
"createdAt": "2024-01-01T00:00:00.000Z"
}
}
使用示例
前端JavaScript示例
// 建立WebSocket连接
const ws = new WebSocket('ws://localhost:3000/ws/notice');
// 连接成功后认证
ws.onopen = () => {
ws.send(JSON.stringify({
event: 'authenticate',
data: { userId: 123 }
}));
};
// 接收通知
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === 'notice') {
console.log('收到新通知:', message.data);
// 在UI中显示通知
showNotification(message.data);
}
};
// 获取通知列表
async function getNotices() {
const response = await fetch('/api/notices', {
headers: {
'Authorization': `Bearer ${token}`
}
});
return response.json();
}
// 标记通知为已读
async function markAsRead(noticeId) {
await fetch(`/api/notices/${noticeId}/read`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`
}
});
}
后端使用示例
// 注入NoticeService
constructor(private readonly noticeService: NoticeService) {}
// 发送系统通知
await this.noticeService.sendSystemNotice(
'系统维护通知',
'系统将于今晚22:00进行维护',
userId
);
// 发送广播通知
await this.noticeService.sendBroadcast(
'新功能上线',
'我们上线了新的通知功能!'
);
// 创建定时通知
await this.noticeService.create({
title: '会议提醒',
content: '您有一个会议将在30分钟后开始',
userId: 123,
scheduledAt: new Date(Date.now() + 30 * 60 * 1000).toISOString()
});
数据库表结构
通知表包含以下字段:
id: 主键title: 通知标题content: 通知内容type: 通知类型(system/user/broadcast)status: 通知状态(pending/sent/read/failed)userId: 接收者ID(null表示广播)senderId: 发送者IDscheduledAt: 计划发送时间sentAt: 实际发送时间readAt: 阅读时间metadata: 额外数据(JSON格式)createdAt: 创建时间updatedAt: 更新时间
定时任务
系统每分钟自动检查并发送到期的定时通知。
注意事项
- 需要在主模块中导入
NoticeModule - 确保数据库中存在
notices表 - WebSocket连接需要用户认证
- 定时通知依赖
@nestjs/schedule包