Skip to content

Lets your async functions have local context, accessible from within any call inside them.

Notifications You must be signed in to change notification settings

MGB247/async-context

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

async-context

Lets your async functions have local context, accessible from within any call inside them.

Example 1

Wrap your async functions in the AsyncContext.run function:

function someInnerFunction() {
  console.log(AsyncContext.get("myGlobalData"));
  //{message: "hello"}
}
function yourAsyncFunction() {
  AsyncContext.set("myGlobalData", {message: "hello"});
  someInnerFunction();
}

AsyncContext.run(yourAsyncFunction, [], yourData);

Example 2

ContextSetter can be used to provide multiple functions that set different contexts:

const yourSetters = [
  (data) => {
    AsyncContext.set("requestId", uuid())
  },
  (data) => {
    AsyncContext.set("someOtherGlobalData", {})
  },
]
AsyncContext.run(yourAsyncFunction, yourSetters, yourData);

Example 3 (NestJS)

NestJS Middleware can be used to intercept requests and add context to them which then can be accessed from any subsequent layer:

function contextMiddleware(req: Request, res: Response, next: NextFunction) {
  const yourSetters = [
    (req) => {
      AsyncContext.set("requestId", uuid())
    },
    (req) => {
      AsyncContext.set("someOtherGlobalData", {})
    },
  ];
  AsyncContext.run(next, yourSetters, req);
};

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(contextMiddleware)
      .forRoutes({ path: 'example', method: RequestMethod.GET });
  }
}

//example.controller.ts

@Get('example')
async getExamples() {
  console.log(AsyncContext.get("requestId"));
  //outputs some uuid
}

About

Lets your async functions have local context, accessible from within any call inside them.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published