-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.gateway.ts
More file actions
74 lines (61 loc) · 1.81 KB
/
Copy pathevents.gateway.ts
File metadata and controls
74 lines (61 loc) · 1.81 KB
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
69
70
71
72
73
74
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
ConnectedSocket,
type WsResponse,
type OnGatewayConnection,
type OnGatewayDisconnect,
} from '@nestjs/websockets';
import { from } from 'rxjs';
import type { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import type { Server, Socket } from 'socket.io';
/*
@WebSocketGateway({
cors: {
origin: '*',
},
})
*/
// WebSocket gateway for events - updated port to 8084
@WebSocketGateway(8084, {
path: '/ws',
cors: {
origin: '*',
},
})
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
private getClientQuery(client: Socket): Record<string, unknown> {
return client.handshake.query;
}
public broadcastAll(event_name: string, message: Record<string, unknown>) {
this.server.emit(event_name, message);
}
public handleConnection(client: Socket) {
const { user_id } = this.getClientQuery(client);
console.log('WssGateway: handleConnection', { user_id });
return this.broadcastAll('event', { connected: user_id });
}
public handleDisconnect(client: Socket) {
const { user_id } = this.getClientQuery(client);
console.log('WssGateway: handleDisconnect', { user_id });
return this.broadcastAll('event', { disconnected: user_id });
}
@SubscribeMessage('tick')
handleEvent(@MessageBody() data: unknown, @ConnectedSocket() client: Socket): WsResponse<unknown> {
const event = 'events';
return { event, data };
}
@SubscribeMessage('tick')
findAll(@MessageBody() data: any): Observable<WsResponse<number>> {
return from([1, 2, 3]).pipe(map((item) => ({ event: 'events', data: item })));
}
@SubscribeMessage('identity')
identity(@MessageBody() data: number): number {
return data;
}
}