forked from dnlup/fastify-traps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (72 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict'
const fp = require('fastify-plugin')
function onSignal (signal) {
this.log.warn(`Received Signal: ${signal}`)
this.log.warn('Closing')
}
function onClose () {
this.log.warn('Closed')
}
function onTimeout (timeout) {
this.log.error(`Could not close before ${timeout} ms, forcing exit`)
}
function onError (error) {
this.log.error(error)
}
function onCloseSignal ({ timeout, onSignal, onClose, onTimeout, onError }, signal) {
onSignal(signal)
const timer = setTimeout(() => {
onTimeout(timeout)
process.exit(1)
}, timeout)
// Try to close the fastify instance gracefully
this.close()
.then(() => {
clearTimeout(timer)
onClose()
process.exit()
})
.catch((error) => {
clearTimeout(timer)
onError(error)
process.exit(1)
})
}
function plugin (fastify, opts, next) {
const DEFAULTS = {
timeout: 3e4,
onSignal: onSignal.bind(fastify),
onClose: onClose.bind(fastify),
onTimeout: onTimeout.bind(fastify),
onError: onError.bind(fastify),
strict: true
}
const config = Object.assign({}, DEFAULTS, opts)
for (const func of ['onSignal', 'onClose', 'onTimeout', 'onError']) {
const f = config[func]
if (typeof f !== 'function') {
return next(new TypeError(`${func} must be a function, received ${typeof f}`))
}
}
if (typeof config.timeout !== 'number') {
return next(new TypeError(`timeout must be a number, received ${typeof config.timeout}`))
}
if (config.timeout < 1) {
return next(new RangeError(`timeout must be greater 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']) {
/* istanbul ignore next */
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()
}
module.exports = fp(plugin, {
fastify: '^4.0.0',
name: '@dnlup/fastify-traps'
})