|
| 1 | +import { JwtService } from '@nestjs/jwt'; |
| 2 | +import { Server } from 'socket.io'; |
| 3 | +import { Inject, UseFilters, forwardRef } from '@nestjs/common'; |
| 4 | +import { |
| 5 | + WebSocketGateway, |
| 6 | + WebSocketServer, |
| 7 | + OnGatewayInit, |
| 8 | + OnGatewayConnection, |
| 9 | + OnGatewayDisconnect, |
| 10 | + SubscribeMessage, |
| 11 | +} from '@nestjs/websockets'; |
| 12 | + |
| 13 | +import { WSServiceErrorCatcher } from '@/common/decorators/ws.catch.decorator'; |
| 14 | +import { |
| 15 | + MaterialSocket, |
| 16 | + MaterialAuthMiddleware, |
| 17 | +} from '@/common/middlewares/socket.ideasComment.middleware'; |
| 18 | +import { IdeasCommentsRepository } from '@/base/ideasComments/ideasComments.repository'; |
| 19 | +import { IdeaComment } from '@/base/ideasComments/interfaces/ideasComments.interface'; |
| 20 | + |
| 21 | +@UseFilters(WSServiceErrorCatcher) |
| 22 | +@WebSocketGateway({ |
| 23 | + transports: ['websocket'], |
| 24 | + cors: { |
| 25 | + origin: '*', // to be defined later |
| 26 | + }, |
| 27 | + namespace: 'ideasEquipements', |
| 28 | +}) |
| 29 | +export class IdeasCommentGateway |
| 30 | + implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect |
| 31 | +{ |
| 32 | + constructor( |
| 33 | + @Inject(forwardRef(() => IdeasCommentsRepository)) |
| 34 | + private ideasCommentsRepository: IdeasCommentsRepository, |
| 35 | + private readonly jwtService: JwtService, |
| 36 | + ) {} |
| 37 | + @WebSocketServer() server: Server; |
| 38 | + items = []; |
| 39 | + |
| 40 | + afterInit(server: Server) { |
| 41 | + server.use(MaterialAuthMiddleware(this.jwtService)); |
| 42 | + } |
| 43 | + |
| 44 | + async handleConnection(client: MaterialSocket) { |
| 45 | + client.join(client.roomId); |
| 46 | + client.to(client.roomId).emit('peer-connected', client.id); |
| 47 | + } |
| 48 | + |
| 49 | + async handleDisconnect(client: MaterialSocket) { |
| 50 | + client.to(client.roomId).emit('peer-disconnected', client.id); |
| 51 | + } |
| 52 | + |
| 53 | + @SubscribeMessage('add-comment') |
| 54 | + async addComment(client: MaterialSocket, data: IdeaComment) { |
| 55 | + |
| 56 | + this.items.unshift(data); |
| 57 | + |
| 58 | + client.to(client.roomId).emit('comment-added', this.items[0]); |
| 59 | + } |
| 60 | +} |
0 commit comments