Created
November 24, 2022 09:02
-
-
Save sachin-hg/a35b34d71d9fbe46c239d38b9fa1aba7 to your computer and use it in GitHub Desktop.
Request Context creation example for module federation request context cache
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
// utils/requestContext.js | |
import { createNamespace } from 'cls-hooked' | |
// context variable here may be global, but the data stored is | |
// not shared among different requests | |
const context = createNamespace(`app:requestData`) | |
// use this middleware in your express middleware chain, as early as possible | |
export function expressMiddleware (req, res, next) { | |
context.run(function () { | |
context.set('requestContext', {}) | |
next() | |
}) | |
} | |
export const getFromRequestContext = () => { | |
return context.get('requestContext') | |
} | |
export const addToRequestContext = (slave, container) => { | |
const ctx = context.get('requestContext') | |
ctx[slave] = container | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment