-
-
Notifications
You must be signed in to change notification settings - Fork 587
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add node 14 async-local-storage dev example
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
"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()); |