-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
46 lines (37 loc) · 947 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
40
41
42
43
44
45
46
const fp = require('fastify-plugin');
const fastAls = require('fast-als');
const httpContext = {
get: fastAls.get,
set: fastAls.set
};
const validHooks = [
'onRequest',
'preParsing',
'preValidation',
'preHandler',
'preSerialization',
'onError',
'onSend',
'onResponse'
];
function plugin(fastify, opts, next) {
const defaults = opts.defaults || {};
const hook = opts.hook || 'onRequest';
if (!validHooks.includes(hook)) {
fastify.log.error(`${hook} is not a valid fastify hook. Please use one of the following ${validHooks}`);
}
fastify.addHook('onRequest', (req, res, done) => {
fastAls.runWith(defaults, () => {
done();
});
});
next();
}
module.exports = {
validHooks: validHooks,
httpContext: httpContext,
fastifyHttpContextPlugin: fp(plugin, {
fastify: '2.x',
name: 'fastify-http-context'
})
};