I'd like to use use AsyncLocalStorage in a NestJs Interceptor:
export interface CallHandler<T = any> {
handle(): Observable<T>;
}
export interface NestInterceptor<T = any, R = any> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<R> | Promise<Observable<R>>;
}
The interceptor function gets a next
CallHandler
that returns an Observable
.
I cannot use run in this case (the run callback will exit immediately before the callHandler.handle()
observable has finished):
intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
const asyncLocalStorage = new AsyncLocalStorage();
const myStore = { some: 'data'};
return asyncLocalStorage.run(myStore, () => callHandler.handle());
}
The solution I came up with is this:
const localStorage = new AsyncLocalStorage();
export class MyInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, callHandler: CallHandler): Observable<any> | Promise<Observable<any>> {
const resource = new AsyncResource('AsyncLocalStorage', { requireManualDestroy: true });
const myStore = { some: 'data' };
localStorage.enterWith(myStore);
return callHandler.handle().pipe(
finalize(() => resource.emitDestroy())
);
}
}
This seems to work fine, but I am not sure if this is really correct - and it looks messy and error-prone. So I wonder:
- Is this correct at all?
- Is there a better/cleaner way to handle this?
here is our current solution to the problem:
callHandler
localStorage.run
method