Skip to content

Commit 1ad521e

Browse files
committed
Fix: Initial messages could be lost
The use of await when handling the "initially" WebSocket message may cause incoming messages to be lost. Event handlers like `ws.on('message', ...)` may not get installed until after the asynchronous method completes, so any WebSocket events during that time period aren't handled. Fixes #20
1 parent 84a11a6 commit 1ad521e

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

hapi-plugin-websocket.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ const register = async (server, pluginOptions) => {
217217
/* optionally inject an empty initial message */
218218
if (routeOptions.initially) {
219219
/* inject incoming WebSocket message as a simulated HTTP request */
220-
const response = await server.inject({
220+
server.inject({
221221
/* simulate the hard-coded POST request */
222222
method: "POST",
223223

@@ -233,19 +233,19 @@ const register = async (server, pluginOptions) => {
233233
plugins: {
234234
websocket: { mode: "websocket", ctx, wss, ws, wsf, req, peers, initially: true }
235235
}
236-
})
237-
238-
/* any HTTP redirection, client error or server error response
239-
leads to an immediate WebSocket connection drop */
240-
if (response.statusCode >= 300) {
241-
const annotation = `(HAPI handler reponded with HTTP status ${response.statusCode})`
242-
if (response.statusCode < 400)
243-
ws.close(1002, `Protocol Error ${annotation}`)
244-
else if (response.statusCode < 500)
245-
ws.close(1008, `Policy Violation ${annotation}`)
246-
else
247-
ws.close(1011, `Server Error ${annotation}`)
248-
}
236+
}).then(response => {
237+
/* any HTTP redirection, client error or server error response
238+
leads to an immediate WebSocket connection drop */
239+
if (response.statusCode >= 300) {
240+
const annotation = `(HAPI handler responded with HTTP status ${response.statusCode})`
241+
if (response.statusCode < 400)
242+
ws.close(1002, `Protocol Error ${annotation}`)
243+
else if (response.statusCode < 500)
244+
ws.close(1008, `Policy Violation ${annotation}`)
245+
else
246+
ws.close(1011, `Server Error ${annotation}`)
247+
}
248+
});
249249
}
250250

251251
/* hook into WebSocket message retrieval */

0 commit comments

Comments
 (0)