-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (31 loc) · 851 Bytes
/
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
const fp = require('fastify-plugin')
function fastify204 (fastify, options, done) {
options = Object.assign({
onUndefined: true,
onNull: false,
onEmptyArray: false
}, options)
fastify.addHook('preSerialization', async (request, reply, payload) => {
if (options.onNull && payload === null) {
reply.code(204)
return
}
if (options.onEmptyArray && Array.isArray(payload) && payload.length === 0) {
reply.code(204)
return
}
return payload
})
fastify.addHook('onSend', async (request, reply, payload) => {
if ((options.onUndefined && payload === undefined && reply.statusCode === 200) || reply.statusCode === 204) {
reply.code(204)
return null
}
return payload
})
done()
}
module.exports = fp(fastify204, {
fastify: '5.x',
name: 'fastify-auto-204'
})