I have a JwtAuthGuard from passport package. I want to use AsyncLocalStorage to access the logged-in-user information across application.
My current Approach: Create a Middleware and pass empty store with setter. On the JwtAuthGuard validate method access the store and the store using the setter in the store.
@Injectable()
export class UserAlsMiddleware implements NestMiddleware {
constructor(
private readonly userAls: AsyncLocalStorage<UserContext>
) { }
use(req: any, res: any, next: (error?: Error | any) => void) {
this.userAls.run(new UserContext(), next);
}
}
export class JwtStrategy extends PassportStrategy(Strategy){
constructor( private readonly userAls: AsyncLocalStorage<UserContext>)
validate(params){
// other code
this.userAls.getStore().setContext(userContext) }
}
export class UserContext {
user: User;
setContext(ctx: UserContext) {
Object.assign(this, ctx);
}
}
Does it cause any side effects? Is there any alternate approach?, Thanks.
Please share your thoughts!