Skip to content

Commit

Permalink
Feat(express-http-context): added isolate function
Browse files Browse the repository at this point in the history
  • Loading branch information
Akalanka47000 committed Feb 28, 2024
1 parent 6739ffe commit cca0980
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/express-http-context/src/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export const middleware = (req, res, next) => {
throw new Error("`middleware` cannot be called from the browser code.");
};

export const isolate = (fn) => {
throw new Error("`isolate` cannot be called from the browser code.");
};

export const get = () => null;

export const set = (key, value) => {};
Expand Down
9 changes: 6 additions & 3 deletions packages/express-http-context/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ export const store = new AsyncLocalStorage();

/** Express.js middleware that is responsible for initializing the context for each request. */
export const middleware = (req, res, next) => {
store.run({}, () => {
next();
});
store.run({}, next);
};

/** Runs a given function in an isolated context */
export const isolate = (fn) => {
store.run({}, fn);
};

/**
Expand Down
3 changes: 3 additions & 0 deletions packages/express-http-context/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { AsyncLocalStorage } from "async_hooks";
/** Express.js middleware that is responsible for initializing the context for each request. */
export declare function middleware(req: Request, res: Response, next: NextFunction): void;

/** Runs a given function in an isolated context */
export declare function isolate(fn: Function): void;

/**
* Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
*/
Expand Down

0 comments on commit cca0980

Please sign in to comment.