1
|
|
|
import express from "express"; |
2
|
|
|
|
3
|
|
|
const CACHE_LIFETIME = 30 * 1000; // 30 seconds in milliseconds |
|
|
|
|
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Manages client and bike connections with caching. |
7
|
|
|
*/ |
8
|
|
|
const clientManager = { |
9
|
|
|
/** @type {Array<express.Response>} */ |
10
|
|
|
clients: [], |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @type {Object<string, {res: express.Response | null}>} |
14
|
|
|
*/ |
15
|
|
|
cachedBikeData: {}, |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Adds a new client to the clients array. |
19
|
|
|
* @param {express.Response} client - The client to add. |
20
|
|
|
*/ |
21
|
|
|
addClient(client) { |
22
|
|
|
this.clients.push(client); |
23
|
|
|
}, |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Removes a client from the clients array. |
27
|
|
|
* @param {express.Response} client - The client to remove. |
28
|
|
|
*/ |
29
|
|
|
removeClient(client) { |
30
|
|
|
this.clients = this.clients.filter(c => c !== client); |
31
|
|
|
}, |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Initializes a new bike entry in the cache. |
35
|
|
|
* @param {Number} bikeId - The bike ID. |
36
|
|
|
* @param {express.Response} res - The bike connection response to add. |
37
|
|
|
*/ |
38
|
|
|
addBike(bikeId, res) { |
39
|
|
|
this.cachedBikeData[bikeId] = { |
40
|
|
|
res: res |
41
|
|
|
}; |
42
|
|
|
}, |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Removes a bike's res key (and value) from the cache object |
46
|
|
|
* @param {Number} bikeId - Id of the bike for which to set res to null |
47
|
|
|
*/ |
48
|
|
|
removeBike(bikeId) { |
49
|
|
|
this.cachedBikeData[bikeId].res = null |
50
|
|
|
}, |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Broadcasts a message to all clients. |
54
|
|
|
* @param {Object} message - The message to broadcast. |
55
|
|
|
*/ |
56
|
|
|
broadcastToClients(message) { |
57
|
|
|
message = JSON.stringify(message) |
58
|
|
|
this.clients.forEach(client => client.write(`data: ${message}\n\n`)); |
59
|
|
|
}, |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Broadcasts a message to a specific bike. |
64
|
|
|
* @param {Number} bikeId - The ID of the bike to which the message should be broadcast. |
65
|
|
|
* @param {Object} message - The message to broadcast. |
66
|
|
|
*/ |
67
|
|
|
broadcastToBikes(bikeId, message) { |
68
|
|
|
const bike = this.cachedBikeData[bikeId]; |
69
|
|
|
message = JSON.stringify(message) |
70
|
|
|
|
71
|
|
|
// If statements can be changed to something better. |
72
|
|
|
if (bike && bike.res) { |
73
|
|
|
bike.res.write(`data: ${message}\n\n`); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
if (bikeId == -1) { |
77
|
|
|
for (const [_, bike] of Object.entries(this.cachedBikeData)) { |
|
|
|
|
78
|
|
|
if (bike.res) { |
79
|
|
|
bike.res.write(`data: ${message}\n\n`); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
}; |
85
|
|
|
|
86
|
|
|
export default clientManager; |
87
|
|
|
|