-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
60 lines (50 loc) · 1.45 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
'use strict'
const isPromise = require('node:util').types.isPromise
const fp = require('fastify-plugin')
function fastifyFunky (fastify, opts, next) {
fastify.addHook('preSerialization', (req, res, payload, done) => {
// Handle Either
if (isEither(payload)) {
return resolvePayload(done, payload.left, payload.right, res)
}
// Handle Task
if (isTask(payload)) {
const result = payload()
if (isPromise(result)) {
result
.then((taskResult) => {
if (isEither(taskResult)) {
return resolvePayload(done, taskResult.left, taskResult.right, res)
}
return resolvePayload(done, null, taskResult, res)
})
.catch(done)
return
}
if (isEither(result)) {
return resolvePayload(done, result.left, result.right, res)
}
return resolvePayload(done, null, result, this)
}
done(null, payload)
})
next()
}
function resolvePayload (done, err, result, reply) {
if (typeof result === 'string') {
reply.type('text/plain; charset=utf-8').serializer(String)
}
return done(err, result)
}
function isEither (payload) {
return payload.left || payload.right
}
function isTask (value) {
return typeof value === 'function' && value.length === 0
}
module.exports = fp(fastifyFunky, {
fastify: '5.x',
name: '@fastify/funky'
})
module.exports.default = fastifyFunky
module.exports.fastifyFunky = fastifyFunky