11import { FastifyInstance } from 'fastify' ;
2- import Joi from 'joi' ;
32import WebSocket from 'ws' ;
43import log from '@app/log' ;
54import attackHandler from './handler.attack' ;
65import connectionHandler from './handler.connection' ;
76import shipPositionHandler from './handler.ship-positions' ;
87import { OutgoingMsgType } from '@app/payloads/outgoing' ;
9- import { IncomingMsgType } from '@app/payloads/incoming' ;
8+ import { WsPayload , IncomingMsgType } from '@app/payloads/incoming' ;
9+ import { WsPayloadSchema } from '@app/payloads/schemas' ;
1010import { MessageHandler , MessageHandlerResponse } from './common' ;
1111import { heartbeat , send } from './common' ;
1212
13- type ParsedWsData = {
14- type : IncomingMsgType ;
15- data : unknown ;
16- } ;
17-
18- const WsDataSchema = Joi . object ( {
19- type : Joi . string ( ) . required ( ) ,
20- data : Joi . object ( )
21- } ) ;
22-
2313/**
2414 * Configures a heartbeat for the WSS attached to the given fastify instance.
2515 * @param app {FastifyInstance}
@@ -38,9 +28,9 @@ const MessageHandlers: { [key in IncomingMsgType]: MessageHandler<unknown> } = {
3828 * Find an appropriate handler for the incoming message, and execute it.
3929 * Send a response generated by the handler to the client.
4030 * @param ws {WebSocket}
41- * @param data {ParsedWsData }
31+ * @param data {WsPayload }
4232 */
43- async function _processSocketMessage ( ws : WebSocket , data : ParsedWsData ) {
33+ async function _processSocketMessage ( ws : WebSocket , data : WsPayload ) {
4434 const handler = MessageHandlers [ data . type ] ;
4535 if ( handler ) {
4636 log . trace ( 'processing incoming message: %j' , data ) ;
@@ -78,7 +68,7 @@ export default async function processSocketMessage(
7868 ws : WebSocket ,
7969 data : WebSocket . Data
8070) {
81- let parsed : ParsedWsData ;
71+ let parsed : WsPayload ;
8272
8373 try {
8474 parsed = JSON . parse ( data . toString ( ) ) ;
@@ -87,7 +77,7 @@ export default async function processSocketMessage(
8777 return ;
8878 }
8979
90- const valid = WsDataSchema . validate ( parsed ) ;
80+ const valid = WsPayloadSchema . validate ( parsed ) ;
9181
9282 if ( valid . error ) {
9383 log . warn ( 'client sent an invalid message payload: %j' , parsed ) ;
@@ -99,6 +89,6 @@ export default async function processSocketMessage(
9989 }
10090 } ) ;
10191 } else {
102- _processSocketMessage ( ws , valid . value as ParsedWsData ) ;
92+ _processSocketMessage ( ws , valid . value as WsPayload ) ;
10393 }
10494}
0 commit comments