-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
52 lines (44 loc) · 1.15 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
'use strict'
const fp = require('fastify-plugin')
const { memo, create } = require('asyncforge')
const app = memo('fastify.app')
const request = memo('fastify.request')
const reply = memo('fastify.reply')
const logger = memo('fastify.logger')
const fastifyAsyncForge = fp(function (fastify, opts, next) {
fastify.decorate('runInAsyncScope', function (fn) {
const store = create()
return store.run(() => {
app.set(this)
logger.set(this.log)
return fn()
})
})
fastify.decorate('enterWith', function () {
const store = create()
store.enterWith()
app.set(this)
logger.set(this.log)
})
fastify.addHook('onRequest', function (req, res, next) {
const store = create()
// We use callbacks because we cannot propagate through async/await
store.run(() => {
app.set(this)
request.set(req)
reply.set(res)
logger.set(req.log)
next()
})
})
create(() => {
app.set(fastify)
logger.set(fastify.log)
next()
})
})
module.exports = fastifyAsyncForge
module.exports.app = app
module.exports.request = request
module.exports.reply = reply
module.exports.logger = logger