@@ -215,7 +215,10 @@ const register = async (server, pluginOptions) => {
215
215
delete headers [ "accept-encoding" ]
216
216
217
217
/* optionally inject an empty initial message */
218
+ let initially ;
218
219
if ( routeOptions . initially ) {
220
+ let resolveInitially ;
221
+ initially = new Promise ( resolve => resolveInitially = resolve ) ;
219
222
/* inject incoming WebSocket message as a simulated HTTP request */
220
223
server . inject ( {
221
224
/* simulate the hard-coded POST request */
@@ -236,7 +239,10 @@ const register = async (server, pluginOptions) => {
236
239
} ) . then ( response => {
237
240
/* any HTTP redirection, client error or server error response
238
241
leads to an immediate WebSocket connection drop */
239
- if ( response . statusCode >= 300 ) {
242
+ if ( response . statusCode < 300 ) {
243
+ resolveInitially ( true ) ;
244
+ } else {
245
+ resolveInitially ( false ) ;
240
246
const annotation = `(HAPI handler responded with HTTP status ${ response . statusCode } )`
241
247
if ( response . statusCode < 400 )
242
248
ws . close ( 1002 , `Protocol Error ${ annotation } ` )
@@ -252,6 +258,10 @@ const register = async (server, pluginOptions) => {
252
258
if ( routeOptions . frame === true ) {
253
259
/* framed WebSocket communication (correlated request/reply) */
254
260
wsf . on ( "message" , async ( ev ) => {
261
+ if ( initially && ! ( await initially ) ) {
262
+ return ;
263
+ }
264
+
255
265
/* allow application to hook into raw WebSocket frame processing */
256
266
routeOptions . frameMessage . call ( ctx , { ctx, wss, ws, wsf, req, peers } , ev . frame )
257
267
@@ -294,6 +304,10 @@ const register = async (server, pluginOptions) => {
294
304
else {
295
305
/* plain WebSocket communication (uncorrelated request/response) */
296
306
ws . on ( "message" , async ( message ) => {
307
+ if ( initially && ! ( await initially ) ) {
308
+ return ;
309
+ }
310
+
297
311
/* inject incoming WebSocket message as a simulated HTTP request */
298
312
const response = await server . inject ( {
299
313
/* simulate the hard-coded POST request */
@@ -322,6 +336,7 @@ const register = async (server, pluginOptions) => {
322
336
/* hook into WebSocket disconnection */
323
337
ws . on ( "close" , ( ) => {
324
338
/* allow application to hook into WebSocket disconnection */
339
+ /* note that this is done even if the `initially` handler closes the connection */
325
340
routeOptions . disconnect . call ( ctx , { ctx, wss, ws, wsf, req, peers } )
326
341
327
342
/* stop tracking the peer */
@@ -330,6 +345,7 @@ const register = async (server, pluginOptions) => {
330
345
} )
331
346
332
347
/* allow application to hook into WebSocket error processing */
348
+ /* note that this is done even if the `initially` handler closes the connection */
333
349
ws . on ( "error" , ( error ) => {
334
350
routeOptions . error . call ( ctx , { ctx, wss, ws, wsf, req, peers } , error )
335
351
} )
0 commit comments