# All files / modules/notifications notifications.controller.ts

0% Statements 0/46
0% Branches 0/1
0% Functions 0/1
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68

     import Router from '@koa/router';
    import { notificationsService } from './notifications.service';
    import { optionalAuth } from '../../middleware/auth';
    import { prisma } from '../../models';

    const router = new Router({ prefix: '/api/notifications' });

    // 测试用户ID
    const TEST_USER_ID = '1';

    /**
     * 获取通知列表
     * GET /api/notifications
     */
    router.get('/', optionalAuth, async (ctx) => {
      try {
        const userId = ctx.state.user?.userId || TEST_USER_ID;
        const notifications = await notificationsService.getNotifications(String(userId));

        ctx.body = {
          code: 0,
          message: 'success',
          data: notifications,
        };
      } catch (error: any) {
        ctx.body = {
          code: 400,
          message: error.message || '获取通知失败',
        };
      }
    });

    /**
     * 标记通知为已读
     * POST /api/notifications/read
     */
    router.post('/read', optionalAuth, async (ctx) => {
      try {
        const { id } = ctx.request.body as { id: string };
        await notificationsService.markAsRead(id);

        ctx.body = {
          code: 0,
          message: 'success',
        };
      } catch (error: any) {
        ctx.body = {
          code: 400,
          message: error.message || '标记失败',
        };
      }
    });

    /**
     * 全部标记为已读
     * PUT /api/notifications/read-all
     */
    router.put('/read-all', optionalAuth, async (ctx) => {
      const userId = ctx.state.user?.userId || TEST_USER_ID;
      await prisma.notification.updateMany({
        where: { userId: parseInt(String(userId)), isRead: false },
        data: { isRead: true },
      });
      ctx.body = { code: 0, message: 'success' };
    });

    export default router;