Skip to content

Commit 91c9507

Browse files
MomenNanoMomen
andauthored
fixed Method 'GET' already declared for route Error (#62)
* add test and make condition before set handler * simplify the logic Co-authored-by: Momen <[email protected]>
1 parent 73f5f73 commit 91c9507

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ function fastifyWebsocket (fastify, opts, next) {
1313
}
1414
const handle = opts.handle
1515
? (req, res) => opts.handle(req[kWs], req)
16-
: (req, res) => { req[kWs].socket.close() }
16+
: (req, res) => {
17+
req[kWs].socket.close()
18+
}
1719

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

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

38+
if (routeOptions.path === routeOptions.prefix) {
39+
return
40+
}
3641
let wsHandler = routeOptions.wsHandler
3742
let handler = routeOptions.handler
3843

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

5358
if (result && typeof result.catch === 'function') {
54-
result.catch((err) => req[kWs].destroy(err))
59+
result.catch(err => req[kWs].destroy(err))
5560
}
5661
})
5762

test/router.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,3 +336,38 @@ test('Should pass route params to handlers', t => {
336336
})
337337
})
338338
})
339+
340+
test('Should not thow error when register empgy get with prefix', t => {
341+
const fastify = Fastify()
342+
343+
t.tearDown(() => fastify.close())
344+
345+
fastify.register(fastifyWebsocket)
346+
347+
fastify.register(
348+
function (instance, opts, next) {
349+
instance.get('/', { websocket: true }, (connection, req) => {
350+
connection.socket.on('message', message => {
351+
t.equal(message, 'hi from client')
352+
connection.socket.send('hi from server')
353+
})
354+
})
355+
next()
356+
},
357+
{ prefix: '/baz' }
358+
)
359+
360+
fastify.listen(0, err => {
361+
if (err) t.error(err)
362+
363+
const ws = new WebSocket(
364+
'ws://localhost:' + fastify.server.address().port + '/baz/'
365+
)
366+
367+
ws.on('open', () => {
368+
t.pass('Done')
369+
ws.close()
370+
t.end()
371+
})
372+
})
373+
})

0 commit comments

Comments
 (0)