-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient-wrapper.ts
66 lines (57 loc) · 2.21 KB
/
client-wrapper.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
import type { ExerciseAction, UUID } from 'digital-fuesim-manv-shared';
import { Client } from 'digital-fuesim-manv-shared';
import type { ExerciseSocket } from '../exercise-server';
import { exerciseMap } from './exercise-map';
import type { ExerciseWrapper } from './exercise-wrapper';
export class ClientWrapper {
public constructor(private readonly socket: ExerciseSocket) {}
private chosenExercise?: ExerciseWrapper;
private relatedExerciseClient?: Client;
/**
* @param exerciseId The exercise id to be used for the client.
* @param clientName The public name of the client.
* @returns The joined client's id, or undefined when the exercise doesn't exists.
*/
public joinExercise(
exerciseId: string,
clientName: string
): UUID | undefined {
const exercise = exerciseMap.get(exerciseId);
if (!exercise) {
return undefined;
}
this.chosenExercise = exercise;
// Although getRoleFromUsedId may throw an error, this should never happen here
// as the provided id is guaranteed to be one of the ids of the exercise as the exercise
// was fetched with this exact id from the exercise map.
const role = this.chosenExercise.getRoleFromUsedId(exerciseId);
this.relatedExerciseClient = Client.create(clientName, role, undefined);
this.chosenExercise.addClient(this);
return this.relatedExerciseClient.id;
}
/**
* Note that this method simply returns when the client did not join an exercise.
*/
public leaveExercise() {
if (this.chosenExercise === undefined) {
// The client has not joined an exercise. Do nothing.
return;
}
this.chosenExercise.removeClient(this);
}
public get exercise(): ExerciseWrapper | undefined {
return this.chosenExercise;
}
public get client(): Client | undefined {
return this.relatedExerciseClient;
}
public emitAction(action: ExerciseAction) {
this.socket.emit('performAction', action);
}
public disconnect() {
this.chosenExercise = undefined;
if (this.socket.connected) {
this.socket.disconnect();
}
}
}