AsyncLocalStorage.js 829 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. // @ts-check
  2. const { AsyncLocalStorage } = require('node:async_hooks')
  3. /**
  4. * @typedef {Object} RequestContext
  5. * @property {Object.<string, array>} [userFullEmails] - Dictionary mapping userId to an array of full emails
  6. */
  7. /** @type {AsyncLocalStorage<RequestContext>} */
  8. const asyncLocalStorage = new AsyncLocalStorage()
  9. /**
  10. * @param {import("express").Request} req
  11. * @param {import("express").Response} res
  12. * @param {import("express").NextFunction} next
  13. */
  14. function middleware(req, res, next) {
  15. asyncLocalStorage.run({}, next)
  16. }
  17. /**
  18. * Remove a key from the AsyncLocalStorage cache
  19. *
  20. * @param {string} key
  21. */
  22. function removeItem(key) {
  23. const store = asyncLocalStorage.getStore()
  24. if (store?.[key]) {
  25. delete store[key]
  26. }
  27. }
  28. module.exports = {
  29. middleware,
  30. storage: asyncLocalStorage,
  31. removeItem,
  32. }