notifications.service.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { prisma } from '../../models';
  2. import { NotFoundError } from '../../middleware/errorHandler';
  3. /**
  4. * 通知服务
  5. */
  6. export class NotificationsService {
  7. /**
  8. * 获取用户通知列表
  9. */
  10. async getNotifications(userId: string) {
  11. const uid = parseInt(userId);
  12. if (isNaN(uid)) return [];
  13. return await prisma.notification.findMany({
  14. where: { userId: uid },
  15. orderBy: { createdAt: 'desc' },
  16. take: 50,
  17. });
  18. }
  19. /**
  20. * 标记通知为已读(仅限本人的通知)
  21. */
  22. async markAsRead(id: string, userId?: string) {
  23. if (!id) {
  24. throw new NotFoundError('通知不存在');
  25. }
  26. // 归属校验:用 updateMany + userId,只标记属于本人的通知
  27. const uid = userId ? parseInt(userId) : NaN;
  28. const where: any = { id };
  29. if (!isNaN(uid)) where.userId = uid;
  30. const result = await prisma.notification.updateMany({
  31. where,
  32. data: { isRead: true },
  33. });
  34. if (result.count === 0) {
  35. throw new NotFoundError('通知不存在');
  36. }
  37. return result;
  38. }
  39. }
  40. export const notificationsService = new NotificationsService();