-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
53 lines (42 loc) · 1.06 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
"use strict";
const { AsyncLocalStorage } = require("async_hooks");
const { randomUUID } = require("crypto");
const asyncLocalStorage = new AsyncLocalStorage();
module.exports = {
withId: configureArgs(withId),
bindId: configureArgs(bindId),
getId,
setId,
};
function withId(id, work) {
return asyncLocalStorage.run({ id }, () => work());
}
function bindId(id, work) {
return (...args) => asyncLocalStorage.run({ id }, () => work(...args));
}
function configureArgs(func) {
return (id, work) => {
if (!work && isFunction(id)) {
work = id;
id = randomUUID();
}
if (!work) throw new Error("Missing work parameter");
return func(id, work);
};
}
function isFunction(object) {
return typeof object === "function";
}
function getId() {
const store = asyncLocalStorage.getStore();
return store && store.id;
}
function setId(id) {
const store = asyncLocalStorage.getStore();
if (!store) {
throw new Error(
"Missing correlation scope. \nUse bindId or withId to create a correlation scope."
);
}
store.id = id;
}