forked from hpi-sam/digital-fuesim-manv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
join-exercise-handler.ts
55 lines (54 loc) · 1.83 KB
/
join-exercise-handler.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
import type { UUID } from 'digital-fuesim-manv-shared';
import { ValidationErrorWrapper } from '../../utils/validation-error-wrapper';
import type { ExerciseServer, ExerciseSocket } from '../../exercise-server';
import { clientMap } from '../client-map';
import { secureOn } from './secure-on';
export const registerJoinExerciseHandler = (
io: ExerciseServer,
client: ExerciseSocket
) => {
secureOn(
client,
'joinExercise',
(exerciseId: string, clientName: string, callback): void => {
// When this listener is registered the socket is in the map.
const clientWrapper = clientMap.get(client)!;
if (clientWrapper.exercise) {
callback({
success: false,
message: 'The client has already joined an exercise',
expected: false,
});
return;
}
let clientId: UUID | undefined;
try {
clientId = clientMap
.get(client)
?.joinExercise(exerciseId, clientName);
} catch (e: unknown) {
if (e instanceof ValidationErrorWrapper) {
callback({
success: false,
message: `Invalid payload: ${e.errors}`,
expected: false,
});
return;
}
throw e;
}
if (!clientId) {
callback({
success: false,
message: 'The exercise does not exist',
expected: false,
});
return;
}
callback({
success: true,
payload: clientId,
});
}
);
};