import { prisma } from '../../models'; import { NotFoundError } from '../../middleware/errorHandler'; /** * 通知服务 */ export class NotificationsService { /** * 获取用户通知列表 */ async getNotifications(userId: string) { const uid = parseInt(userId); if (isNaN(uid)) return []; return await prisma.notification.findMany({ where: { userId: uid }, orderBy: { createdAt: 'desc' }, take: 50, }); } /** * 标记通知为已读(仅限本人的通知) */ async markAsRead(id: string, userId?: string) { if (!id) { throw new NotFoundError('通知不存在'); } // 归属校验:用 updateMany + userId,只标记属于本人的通知 const uid = userId ? parseInt(userId) : NaN; const where: any = { id }; if (!isNaN(uid)) where.userId = uid; const result = await prisma.notification.updateMany({ where, data: { isRead: true }, }); if (result.count === 0) { throw new NotFoundError('通知不存在'); } return result; } } export const notificationsService = new NotificationsService();