aboutsummaryrefslogtreecommitdiffstats
path: root/backend/src/config/session-store.ts
blob: 283031bb07f22118766bb711f9c69b499aee1c96 (plain)
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
export type Session = {
  id: string;
  state: string;
  host?: string;
  clients: string[];
};

const sessions: { [key: string]: Session } = {};

function makeid(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  let counter = 0;
  while (counter < length) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
    counter += 1;
  }
  return result;
}


export const createNewSession = (): Session => {
  const id = makeid(10);
  const session = {
    id,
    state: "waiting",
    host: undefined,
    clients: [],
  };
  sessions[id] = session;
  return session;
};

export const setSessionState = (id: string, state: string): void => {
  if (!sessions[id]) {
    return;
  }

  sessions[id].state = state;
};

export const setSessionHost = (id: string, clientId: string): void => {
  if (!sessions[id]) {
    return;
  }

  sessions[id].host = clientId;
};

export const addSessionClient = (id: string, clientId: string): void => {
  if (!sessions[id]) {
    return;
  }

  sessions[id]?.clients.push(clientId);
};

export const cleanupSession = (id: string): void => {
  if (!sessions[id]) {
    return;
  }

//  if (sessions[id].host) {
//    sessions[id].host!.close();
//  }
//  
//  sessions[id].clients.forEach((client) => {
//    client.close();
//  });

  delete sessions[id];
}

export const getSession = (id: string): Session => {
  return sessions[id];
};