-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathboard-trees.gateway.ts
78 lines (70 loc) ยท 2.15 KB
/
board-trees.gateway.ts
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
75
76
77
78
import { UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import {
OnGatewayConnection,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { BoardTreesService } from './board-trees.service';
import {
OperationAdd,
OperationDelete,
OperationMove,
OperationUpdate,
} from '../crdt/operation';
@WebSocketGateway({ namespace: 'board' })
export class BoardTreesGateway implements OnGatewayConnection {
constructor(
private boardTreesService: BoardTreesService,
private jwtService: JwtService,
) {}
@WebSocketServer()
server: Server;
handleConnection(client: Socket, token: string) {
if (!token) {
client.disconnect();
throw new UnauthorizedException();
}
try {
this.jwtService.verify(token);
} catch (error) {
client.disconnect();
throw new UnauthorizedException();
}
}
@SubscribeMessage('joinBoard')
async handleJoinBoard(client: Socket, payload: string) {
const payloadObject = JSON.parse(payload);
if (!this.boardTreesService.hasTree(payloadObject.boardId)) {
await this.boardTreesService.initBoardTree(
payloadObject.boardId,
payloadObject.boardName,
);
}
client.join(payloadObject.boardId);
client.emit(
'initTree',
this.boardTreesService.getTreeData(payloadObject.boardId),
);
}
@SubscribeMessage('updateMindmap')
handleUpdateMindmap(client: Socket, payload: string) {
const payloadObject = JSON.parse(payload);
const { boardId, operation: serializedOperation } = payloadObject;
const operationTypeMap = {
add: OperationAdd.parse<string>,
delete: OperationDelete.parse<string>,
move: OperationMove.parse<string>,
update: OperationUpdate.parse<string>,
};
const operation =
operationTypeMap[serializedOperation.operationType](serializedOperation);
this.boardTreesService.applyOperation(boardId, operation);
this.boardTreesService.updateTreeData(boardId);
client.broadcast
.to(boardId)
.emit('operationFromServer', serializedOperation);
}
}