(event: ws.MessageEvent, data: SocketRequestData | SocketResponseData<any>)
| 325 | } |
| 326 | |
| 327 | protected async handleMessage(event: ws.MessageEvent, data: SocketRequestData | SocketResponseData<any>): Promise<void> { |
| 328 | // Prepare event |
| 329 | |
| 330 | const client = this.clients.clients.find(client => client.socket === event.target); |
| 331 | |
| 332 | if (!client) { |
| 333 | console.error('Failed to handle message. No client was found for the socket.'); |
| 334 | return; |
| 335 | } |
| 336 | |
| 337 | const msg_event: MsgEvent = { |
| 338 | wsEvent: event, |
| 339 | client: client, |
| 340 | }; |
| 341 | |
| 342 | this.lastClient = client; // Cheap hack for targeting what client to send misc. requests to |
| 343 | |
| 344 | // Handle |
| 345 | |
| 346 | const start = performance.now(); |
| 347 | const [inc, out] = await api_handle_message(this.api, data, msg_event); |
| 348 | const end = performance.now(); |
| 349 | if (VERBOSE.enabled && 'type' in data && data.type !== BackIn.KEEP_ALIVE) { |
| 350 | console.log(`${Math.floor(end - start)}ms - "${BackIn[data.type]}"`); |
| 351 | } |
| 352 | |
| 353 | if (inc) { |
| 354 | const sent = client.sent.find(s => s.id === data.id); |
| 355 | if (sent) { |
| 356 | sent.resolve(inc as SocketResponseData<any>); |
| 357 | } else { |
| 358 | console.error(`Received a response with an ID that does not match any sent request from that client! (response id: ${data.id}, client id: ${client.id})`); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | if (out) { |
| 363 | if ('type' in data && 'result' in out) { |
| 364 | const res = { |
| 365 | type: data.type as BackRes, |
| 366 | res: out.result as ReturnType<BackResTemplate[BackRes]> |
| 367 | }; |
| 368 | try { |
| 369 | // Call middleware |
| 370 | await this.middlewareRes.execute(res); |
| 371 | // Modify output |
| 372 | out.result = res.res; |
| 373 | } catch (err) { |
| 374 | if (res.type !== BackOut.LOG_ENTRY_ADDED) { |
| 375 | log.info('Launcher', 'Error in middleware - Type: ' + BackRes[res.type]); |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | event.target.send(JSON.stringify(out)); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | type StartServerResult = { |
no test coverage detected