import { Controller, Get, Param, Query, Req, Sse, UnauthorizedException, UseGuards } from '@nestjs/common'; import { AuthenticatedRequest } from 'src/model/interface/authenticated-request.interface'; import { SseTicketService } from './sse-ticket.service'; import { AuthGuard } from 'src/core/guards/auth.guard'; import { finalize, Observable } from 'rxjs'; import { SseService } from './sse.service'; @Controller('sse') export class SseController { constructor(private ticketService: SseTicketService, private sseService: SseService) {} @UseGuards(AuthGuard) @Get('ticket') getTicket(@Req() req: AuthenticatedRequest) { return this.ticketService.generateTicket(req.user.id) } @Sse('key') async sse(@Query('ticket') ticket: string): Promise> { const userId = this.ticketService.getUserIdToTicket(ticket); if (!userId) throw new UnauthorizedException('Invalid/expired ticket'); if (!userId) throw new UnauthorizedException('Invalid/expired ticket'); return this.sseService.register(userId).pipe( finalize(() => { this.sseService.unregister(userId) }) ); } }