Skip to content

Commit

Permalink
feat: check if there are other handlers
Browse files Browse the repository at this point in the history
Error if there are other handlers for the signals, but allow to override
this behavior for testing.
  • Loading branch information
dnlup committed Nov 5, 2020
1 parent be20057 commit 658597e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ function plugin (fastify, opts, next) {
onClose: onClose.bind(fastify),
onTimeout: onTimeout.bind(fastify),
onError: onError.bind(fastify),
timeout: 2000
timeout: 2000,
strict: true
}
const config = Object.assign({}, DEFAULTS, opts)

Expand All @@ -63,8 +64,14 @@ function plugin (fastify, opts, next) {
if (config.timeout < 1) {
return next(new RangeError(`timeout must be greather than 0, received ${config.timeout}`))
}
if (typeof config.strict !== 'boolean') {
return next(new TypeError(`strict must be a boolean, received ${typeof config.strict}`))
}

for (const signal of ['SIGINT', 'SIGTERM']) {
if (config.strict && process.listenerCount(signal) > 0) {
return next(new Error(`A ${signal} handler is already registered`))
}
process.once(signal, onCloseSignal.bind(fastify, config))
}
next()
Expand Down
12 changes: 10 additions & 2 deletions test/plugin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,19 @@ test('invalid options', async t => {
timeout: 0
},
error: new RangeError('timeout must be greather than 0, received 0')
},
{
opts: {
strict: 'true'
},
error: new TypeError('strict must be a boolean, received string')
}
]

for (const [index, item] of list.entries()) {
const fastify = Fastify()
await t.rejects(() => fastify.register(plugin, item.opts), item.error, `item ${index}`)
const opts = Object.assign({}, item.opts, item.opts.strict ? {} : { strict: false })
await t.rejects(() => fastify.register(plugin, opts), item.error, `item ${index}`)
}
t.end()
})
Expand Down Expand Up @@ -82,7 +89,8 @@ test('valid options', async t => {

for (const [index, item] of list.entries()) {
const fastify = Fastify()
await t.resolves(() => fastify.register(plugin, item.opts), `item ${index}`)
const opts = Object.assign({}, item.opts, { strict: false })
await t.resolves(() => fastify.register(plugin, opts), `item ${index}`)
}
t.end()
})
Expand Down

0 comments on commit 658597e

Please sign in to comment.