Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,11 @@ function fastifyWebsocket (fastify, opts, next) {
let handler = routeOptions.handler

if (routeOptions.websocket || routeOptions.wsHandler) {
if (routeOptions.method === 'HEAD') {
// `method` can also be an array, e.g. ['GET', 'HEAD']
const methods = Array.isArray(routeOptions.method) ? routeOptions.method : [routeOptions.method]
if (methods.every(method => method === 'HEAD')) {
return
} else if (routeOptions.method !== 'GET') {
} else if (methods.some(method => method !== 'GET' && method !== 'HEAD')) {
throw new Error('websocket handler can only be declared in GET method')
}

Expand Down
37 changes: 37 additions & 0 deletions test/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,43 @@ test('Should throw on wrong HTTP method', (t, end) => {
})
})

test('Should accept an array of GET methods', async t => {
for (const method of [['GET'], ['GET', 'HEAD']]) {
const fastify = Fastify()
t.after(() => fastify.close())

await fastify.register(fastifyWebsocket)
fastify.route({
method,
url: '/echo',
websocket: true,
handler: (socket) => {
socket.once('message', message => socket.send(message))
}
})
await fastify.ready()

const ws = await fastify.injectWS('/echo')
const reply = new Promise(resolve => ws.once('message', data => resolve(data.toString())))
ws.send('hi')
t.assert.strictEqual(await reply, 'hi')
ws.terminate()
}
})

test('Should throw on an array with a non-GET method', async t => {
const fastify = Fastify()
t.after(() => fastify.close())

await fastify.register(fastifyWebsocket)
t.assert.throws(() => fastify.route({
method: ['GET', 'POST'],
url: '/echo',
websocket: true,
handler: () => {}
}), { message: 'websocket handler can only be declared in GET method' })
})

test('Should throw on invalid wsHandler', async t => {
t.plan(1)
const fastify = Fastify()
Expand Down