From fb61e56de5bd291965b32cf7f2e8094c4d750aa4 Mon Sep 17 00:00:00 2001 From: thetutlage Date: Tue, 17 Jul 2018 12:18:47 +0530 Subject: [PATCH] fix(server): allow trailing slashes in request url fix #57 --- src/Ws/index.js | 8 ++++++++ test/functional/ws.spec.js | 9 ++++++++- test/unit/ws.spec.js | 9 +++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Ws/index.js b/src/Ws/index.js index 47414f0..037af3f 100644 --- a/src/Ws/index.js +++ b/src/Ws/index.js @@ -10,6 +10,7 @@ */ const WebSocket = require('ws') +const url = require('url') const GE = require('@adonisjs/generic-exceptions') const Connection = require('../Connection') const ClusterHop = require('../ClusterHop') @@ -240,6 +241,13 @@ class Ws { listen (server) { this._wsServer = new WebSocket.Server(Object.assign({}, this._serverOptions, { server })) + /** + * Override the shouldHandle method to allow trailing slashes + */ + this._wsServer.shouldHandle = function (req) { + return this.options.path && url.parse(req.url).pathname.replace(/\/$/, '') === this.options.path + } + /** * Listening for new connections */ diff --git a/test/functional/ws.spec.js b/test/functional/ws.spec.js index 9c305c8..507e3f3 100644 --- a/test/functional/ws.spec.js +++ b/test/functional/ws.spec.js @@ -335,7 +335,7 @@ test.group('Ws', (group) => { const client2 = helpers.startClient({}, '/adonis-ws') client2.on('open', () => joinChannel(client2)) client2.on('message', onMessage) - }) + }).timeout(0) test('broadcast messages to all clients', (assert, done) => { let connectedClients = [] @@ -449,4 +449,11 @@ test.group('Ws', (group) => { client2.on('open', () => joinChannel(client2, 'chat:frontend')) client2.on('message', onMessage) }) + + test('work fine with slash in the end', (assert, done) => { + const client = helpers.startClient({}, '/adonis-ws/') + client.on('open', () => { + done() + }) + }) }) diff --git a/test/unit/ws.spec.js b/test/unit/ws.spec.js index db3d6d4..6bd4eb3 100644 --- a/test/unit/ws.spec.js +++ b/test/unit/ws.spec.js @@ -159,4 +159,13 @@ test.group('Ws', (group) => { } }) }) + + test('work fine with slash in the end', (assert, done) => { + this.ws = new Ws(new Config()) + this.httpServer = helpers.startHttpServer() + this.ws.listen(this.httpServer) + + const client = helpers.startClient({}, '/adonis-ws/') + client.on('open', () => done()) + }) })