diff --git a/apps/server/src/notifications/notifications.controller.ts b/apps/server/src/notifications/notifications.controller.ts new file mode 100644 index 0000000..82213c4 --- /dev/null +++ b/apps/server/src/notifications/notifications.controller.ts @@ -0,0 +1,79 @@ +import { + Controller, + Get, + Put, + Param, + Query, + Req, + Sse, + UseGuards, +} from '@nestjs/common'; +import { Request } from 'express'; +import { Observable, map } from 'rxjs'; +import { NotificationsService } from './notifications.service'; +import { NotificationQueryDto } from './dto/notification.dto'; +import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; + +interface AuthenticatedUser { + id: number; + username: string; + permissions: string[]; +} + +interface AuthenticatedRequest extends Request { + user: AuthenticatedUser; +} + +@UseGuards(JwtAuthGuard) +@Controller('notifications') +export class NotificationsController { + constructor(private readonly service: NotificationsService) {} + + @Get() + async findAll( + @Req() req: AuthenticatedRequest, + @Query() query: NotificationQueryDto, + ) { + const userId = req.user.id; + return this.service.findByUser(userId, query.after, query.limit ?? 20); + } + + @Get('unread-count') + async unreadCount(@Req() req: AuthenticatedRequest) { + const userId = req.user.id; + const count = await this.service.getUnreadCount(userId); + return { count }; + } + + @Sse('stream') + stream(@Req() req: AuthenticatedRequest): Observable { + const userId = req.user.id; + return this.service.subscribe(userId).pipe( + map((notification) => ({ + data: JSON.stringify({ + id: notification.id, + type: notification.type, + title: notification.title, + content: notification.content, + link: notification.link, + createdAt: notification.createdAt, + }), + } as MessageEvent)), + ); + } + + @Put(':id/read') + async markRead( + @Param('id') id: string, + @Req() req: AuthenticatedRequest, + ) { + await this.service.markRead(+id, req.user.id); + return { success: true }; + } + + @Put('read-all') + async markAllRead(@Req() req: AuthenticatedRequest) { + await this.service.markAllRead(req.user.id); + return { success: true }; + } +} diff --git a/apps/server/src/notifications/notifications.module.ts b/apps/server/src/notifications/notifications.module.ts index 4e3ccb8..f79a7bf 100644 --- a/apps/server/src/notifications/notifications.module.ts +++ b/apps/server/src/notifications/notifications.module.ts @@ -2,9 +2,11 @@ import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Notification } from '../entities/notification.entity'; import { NotificationsService } from './notifications.service'; +import { NotificationsController } from './notifications.controller'; @Module({ imports: [TypeOrmModule.forFeature([Notification])], + controllers: [NotificationsController], providers: [NotificationsService], exports: [NotificationsService], })