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
|
|
|
* @returns {void} |
22
|
|
|
*/ |
23
|
|
|
addClient(client) { |
24
|
|
|
this.clients.push(client); |
25
|
|
|
}, |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Removes a client from the clients array. |
29
|
|
|
* @param {express.Response} client - The client to remove. |
30
|
|
|
* |
31
|
|
|
* @returns {void} |
32
|
|
|
*/ |
33
|
|
|
removeClient(client) { |
34
|
|
|
this.clients = this.clients.filter(c => c !== client); |
35
|
|
|
}, |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Initializes a new bike entry in the cache. |
39
|
|
|
* @param {Number} bikeId - The bike ID. |
40
|
|
|
* @param {express.Response} res - The bike connection response to add. |
41
|
|
|
* |
42
|
|
|
* @returns {void} |
43
|
|
|
*/ |
44
|
|
|
addBike(bikeId, res) { |
45
|
|
|
this.cachedBikeData[bikeId] = { |
46
|
|
|
res: res |
47
|
|
|
}; |
48
|
|
|
}, |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Removes a bike's res key (and value) from the cache object |
52
|
|
|
* @param {Number} bikeId - Id of the bike for which to set res to null |
53
|
|
|
* |
54
|
|
|
* @returns {void} |
55
|
|
|
*/ |
56
|
|
|
removeBike(bikeId) { |
57
|
|
|
this.cachedBikeData[bikeId].res = null |
58
|
|
|
}, |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Broadcasts a message to all clients. |
62
|
|
|
* @param {Object} message - The message to broadcast. |
63
|
|
|
* |
64
|
|
|
* @returns {void} |
65
|
|
|
*/ |
66
|
|
|
broadcastToClients(message) { |
67
|
|
|
message = JSON.stringify(message) |
68
|
|
|
this.clients.forEach(client => client.write(`data: ${message}\n\n`)); |
69
|
|
|
}, |
70
|
|
|
|
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Broadcasts a message to a specific bike. |
74
|
|
|
* @param {Number} bikeId - The ID of the bike to which the message should be broadcast. |
75
|
|
|
* @param {Object} message - The message to broadcast. |
76
|
|
|
* |
77
|
|
|
* @returns {void} |
78
|
|
|
*/ |
79
|
|
|
broadcastToBikes(bikeId, message) { |
80
|
|
|
message = JSON.stringify(message) |
81
|
|
|
|
82
|
|
|
if (bikeId === -1) { |
83
|
|
|
Object.values(this.cachedBikeData).forEach(bike => { |
84
|
|
|
bike.res?.write(`data: ${message}\n\n`); |
85
|
|
|
}); |
86
|
|
|
return; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
this.cachedBikeData[bikeId]?.res?.write(`data: ${message}\n\n`); |
90
|
|
|
} |
91
|
|
|
}; |
92
|
|
|
|
93
|
|
|
export default clientManager; |
94
|
|
|
|