-
Notifications
You must be signed in to change notification settings - Fork 225
/
async-hooks.js
35 lines (28 loc) · 1.01 KB
/
async-hooks.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
'use strict'
const asyncHooks = require('async_hooks')
module.exports = function (ins) {
const asyncHook = asyncHooks.createHook({init, destroy})
const transactions = new Map()
Object.defineProperty(ins, 'currentTransaction', {
get () {
const asyncId = asyncHooks.executionAsyncId()
return transactions.has(asyncId) ? transactions.get(asyncId) : null
},
set (trans) {
const asyncId = asyncHooks.executionAsyncId()
transactions.set(asyncId, trans)
}
})
asyncHook.enable()
function init (asyncId, type, triggerAsyncId, resource) {
// We don't care about the TIMERWRAP, as it will only init once for each
// timer that shares the timeout value. Instead we rely on the Timeout
// type, which will init for each scheduled timer.
if (type === 'TIMERWRAP') return
transactions.set(asyncId, ins.currentTransaction)
}
function destroy (asyncId) {
if (!transactions.has(asyncId)) return // in case type === TIMERWRAP
transactions.delete(asyncId)
}
}