Created
August 12, 2022 17:32
-
-
Save rcoedo/4bf5e6c377b52d5fd1ff1d555c6a369e to your computer and use it in GitHub Desktop.
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
const { createNamespace } = require("cls-hooked"); | |
const ns = createNamespace("myApp"); |
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
const requestIdMiddleware = (req, res, next) => { | |
ns.run(() => { | |
ns.set("requestId", uuid()); | |
next(); | |
}); | |
}; |
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
const express = require("express"); | |
const { createNamespace } = require("cls-hooked"); | |
const uuid = require("uuid/v4"); | |
const ns = createNamespace("myApp"); | |
const requestIdMiddleware = (req, res, next) => { | |
ns.run(() => { | |
ns.set("requestId", uuid()); | |
next(); | |
}); | |
}; | |
const app = express(); | |
app.use(requestIdMiddleware); | |
app.get("/", (req, res) => { | |
console.log(`[${ns.get("requestId")}] request received`); | |
res.send("It works!"); | |
}); | |
const port = process.env.PORT || 3000; | |
app.listen(port, () => console.log(`Express server listening on port ${port}`)); |
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
This gist contains the examples for the article "Continuation Local Storage for Easy Context Passing in Node.js". | |
- https://medium.com/trabe/continuation-local-storage-for-easy-context-passing-in-node-js-2461c2120284 | |
- https://rcoedo.com/blog/2019/11/14/continuation-local-storage-for-easy-context-passing-in-node-js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment