Created
August 13, 2022 11:32
-
-
Save rcoedo/ab9af352c6fb58279f752ce85099d756 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 { AsyncLocalStorage } = require("async_hooks"); | |
const asyncLocalStorage = new AsyncLocalStorage(); |
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) => { | |
asyncLocalStorage.run(new Map(), () => { | |
asyncLocalStorage.getStore().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 { AsyncLocalStorage } = require("async_hooks"); | |
const uuid = require("uuid/v4"); | |
const asyncLocalStorage = new AsyncLocalStorage(); | |
const requestIdMiddleware = (req, res, next) => { | |
asyncLocalStorage.run(new Map(), () => { | |
asyncLocalStorage.getStore().set("requestId", uuid()); | |
next(); | |
}); | |
}; | |
const app = express(); | |
app.use(requestIdMiddleware); | |
app.get("/", (req, res) => { | |
const id = asyncLocalStorage.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}`)); |
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 "AsyncLocalStorage for Easy Context Passing in Node.js". | |
- https://medium.com/trabe/asynclocalstorage-for-easy-context-passing-in-node-js-e33c84679516 | |
- https://rcoedo.com/blog/2020/05/25/async-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