Skip to content

Commit

Permalink
fixed Method 'GET' already declared for route Error (#62)
Browse files Browse the repository at this point in the history
* add test and make condition before set handler

* simplify the logic

Co-authored-by: Momen <[email protected]>
  • Loading branch information
MomenNano and Momen authored May 27, 2020
1 parent 73f5f73 commit 91c9507
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ function fastifyWebsocket (fastify, opts, next) {
}
const handle = opts.handle
? (req, res) => opts.handle(req[kWs], req)
: (req, res) => { req[kWs].socket.close() }
: (req, res) => {
req[kWs].socket.close()
}

const options = Object.assign({ server: fastify.server }, opts.options)

Expand All @@ -33,6 +35,9 @@ function fastifyWebsocket (fastify, opts, next) {
throw new Error('websocket handler can only be declared in GET method')
}

if (routeOptions.path === routeOptions.prefix) {
return
}
let wsHandler = routeOptions.wsHandler
let handler = routeOptions.handler

Expand All @@ -51,7 +56,7 @@ function fastifyWebsocket (fastify, opts, next) {
const result = wsHandler(req[kWs], req, params)

if (result && typeof result.catch === 'function') {
result.catch((err) => req[kWs].destroy(err))
result.catch(err => req[kWs].destroy(err))
}
})

Expand Down
35 changes: 35 additions & 0 deletions test/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,38 @@ test('Should pass route params to handlers', t => {
})
})
})

test('Should not thow error when register empgy get with prefix', t => {
const fastify = Fastify()

t.tearDown(() => fastify.close())

fastify.register(fastifyWebsocket)

fastify.register(
function (instance, opts, next) {
instance.get('/', { websocket: true }, (connection, req) => {
connection.socket.on('message', message => {
t.equal(message, 'hi from client')
connection.socket.send('hi from server')
})
})
next()
},
{ prefix: '/baz' }
)

fastify.listen(0, err => {
if (err) t.error(err)

const ws = new WebSocket(
'ws://localhost:' + fastify.server.address().port + '/baz/'
)

ws.on('open', () => {
t.pass('Done')
ws.close()
t.end()
})
})
})

0 comments on commit 91c9507

Please sign in to comment.