Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcoedo/b27f86aad4f5be88d87593da15013b80 to your computer and use it in GitHub Desktop.
Save rcoedo/b27f86aad4f5be88d87593da15013b80 to your computer and use it in GitHub Desktop.
const { AsyncLocalStorage } = require("async_hooks");
const { v4: uuid } = require("uuid");
const defaultStore = new Map();
defaultStore.set("requestId", "not-in-a-request");
const context = new AsyncLocalStorage();
context.enterWith(defaultStore);
const middleware = (req, res, next) => {
context.run(new Map(), () => {
context.getStore().set("requestId", uuid());
next();
});
};
module.exports = {
context,
middleware,
};
const express = require("express");
const ctx = require("./context.js");
const app = express();
app.use(ctx.middleware);
app.get("/", (req, res) => {
const id = ctx.context.getStore().get("requestId");
console.log(`[${id}] request received`);
res.send("It works!");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Express server listening on port ${port}`));
module.exports = {
get requestId() {
return context.getStore().get("requestId");
},
middleware,
};
const express = require("express");
const ctx = require("./context.js");
const app = express();
app.use(ctx.middleware);
app.get("/", (req, res) => {
console.log(`[${ctx.requestId}] request received`);
res.send("It works!");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Express server listening on port ${port}`));
const express = require("express");
const { middleware, requestId } = require("./context.js"); // Now we're destructuring the module here.
const app = express();
app.use(middleware);
app.get("/", (req, res) => {
console.log(`[${requestId}] request received`); // We still use the requestId here.
res.send("It works!");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Express server listening on port ${port}`));
This gist contains the examples for the article "Context-Dependent Imports Using CLS and Getters".
- https://medium.com/trabe/context-dependent-imports-using-cls-and-getters-71b97c1baf3c
- https://rcoedo.com/blog/2020/06/15/context-dependent-imports-using-cls-and-getters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment