Skip to content

Commit

Permalink
add node 14 async-local-storage dev example
Browse files Browse the repository at this point in the history
  • Loading branch information
icebob committed Aug 6, 2020
1 parent 310e906 commit 6afcd49
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions dev/async-local-storage.js
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());

0 comments on commit 6afcd49

Please sign in to comment.