Skip to content

Commit

Permalink
feat: added hook to close socket server on fastify close
Browse files Browse the repository at this point in the history
  • Loading branch information
alemagio committed Feb 3, 2021
1 parent ee94ee3 commit 1e15892
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@ const fp = require('fastify-plugin')

module.exports = fp(async function (fastify, opts) {
fastify.decorate('io', require('socket.io')(fastify.server, opts))
fastify.addHook('onClose', (fastify, done) => {
fastify.io.close()
done()
})
}, { fastify: '3.x' })
41 changes: 41 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,44 @@ test('should register the correct decorator passing options', async t => {
})
)
})

test('should close socket server on fastify close', async t => {
t.plan(1)

const { once } = require('events')

const PORT = 3030
const server = require('http').Server()
server.on('error', (e) => {
console.log(e)
if (e.code === 'EADDRINUSE') {
t.fail('Port was not free!')
setTimeout(() => {
server.close()
server.listen(PORT)
}, 1000)
}
})

const app = require('fastify')()

app.register(require('..'), {
path: '/test',
serveClient: false,
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
})

await app.ready()
app.io.listen(PORT)

await app.close()

server.listen(PORT)

await once(server, 'listening')

server.close()
t.ok(true)
})

0 comments on commit 1e15892

Please # to comment.