-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.gateway.ts
More file actions
65 lines (56 loc) · 2.07 KB
/
Copy pathevents.gateway.ts
File metadata and controls
65 lines (56 loc) · 2.07 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
import { Logger } from '@nestjs/common';
import {
OnGatewayConnection,
OnGatewayDisconnect,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { DefaultEventsMap, Server, Socket } from 'socket.io';
import { Task } from '../tasks/entities/task.entity';
import { TASK_EVENTS } from './task-events';
/**
* Typed server→client event contract. Emitting a wrong payload for an event
* (or a typo'd event name) is now a compile error, not a runtime surprise.
*/
interface TaskBroadcastEvents {
[TASK_EVENTS.Created]: (task: Task) => void;
[TASK_EVENTS.Updated]: (task: Task) => void;
[TASK_EVENTS.Deleted]: (task: Task) => void;
}
type TaskServer = Server<DefaultEventsMap, TaskBroadcastEvents>;
/**
* Broadcasts task mutations to connected clients. The tasks service calls the
* helpers below after every successful mutation, fanning the *full* updated
* task out to every client connected to THIS instance.
*
* Data flows one way (service → gateway → clients) and the gateway has no
* dependency on the tasks service, keeping the dependency graph acyclic. CORS
* is configured centrally by `ConfiguredIoAdapter`, not hardcoded here.
*
* NOTE: `server.emit` reaches only clients on the current process. For a
* horizontally-scaled deployment, plug a Redis (or other) Socket.IO adapter
* into `ConfiguredIoAdapter` so broadcasts fan out across instances.
*/
@WebSocketGateway()
export class EventsGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
private readonly logger = new Logger(EventsGateway.name);
@WebSocketServer()
private server!: TaskServer;
handleConnection(client: Socket): void {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket): void {
this.logger.log(`Client disconnected: ${client.id}`);
}
broadcastCreated(task: Task): void {
this.server.emit(TASK_EVENTS.Created, task);
}
broadcastUpdated(task: Task): void {
this.server.emit(TASK_EVENTS.Updated, task);
}
broadcastDeleted(task: Task): void {
this.server.emit(TASK_EVENTS.Deleted, task);
}
}