-
-
Notifications
You must be signed in to change notification settings - Fork 588
/
Copy pathasync-local-storage.js
50 lines (43 loc) · 1.14 KB
/
async-local-storage.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
"use strict";
/**
* Testing the new AsyncLocalStorage module
* to store the current context in the action into the async local storage.
*
* Please note it works only >= Node 14.
*/
const ServiceBroker = require("../src/service-broker");
const { AsyncLocalStorage } = require("async_hooks");
const asyncLocalStorage = new AsyncLocalStorage();
const AsyncLocalStorageMiddleware = {
localAction(handler) {
return ctx => asyncLocalStorage.run(ctx, () => handler(ctx));
}
};
// Create broker
const broker = new ServiceBroker({
middlewares: [AsyncLocalStorageMiddleware]
});
broker.createService({
name: "greeter",
actions: {
hello: {
async handler(ctx) {
await this.doSomething();
return `Hello ${ctx.params.name}`;
}
}
},
methods: {
async doSomething() {
await Promise.resolve().delay(500);
const ctx = asyncLocalStorage.getStore();
console.log("Current context params:", ctx ? ctx.params : "<No context>");
}
}
});
broker
.start()
.then(() => broker.call("greeter.hello", { name: "Moleculer" }))
.then(res => broker.logger.info("Result:", res))
.catch(err => broker.logger.error(err))
.then(() => broker.stop());