Skip to content

Instantly share code, notes, and snippets.

@islahh
Created April 8, 2023 08:01
Show Gist options
  • Save islahh/223e6f2dd64fb11d3ccf2b55e2811ee9 to your computer and use it in GitHub Desktop.
Save islahh/223e6f2dd64fb11d3ccf2b55e2811ee9 to your computer and use it in GitHub Desktop.
Create async local storage using node JS async_hooks in NestJS
// user.storage.ts
import { AsyncLocalStorage } from 'async_hooks';
export interface User {
id: string;
}
export const UserStorage = {
storage: new AsyncLocalStorage<User>(),
get() {
return this.storage.getStore();
},
set(user: User) {
return this.storage.enterWith(user);
},
};
<!-- Set and Get user object -->
<!-- Set user object during right after authenticated -->
async validate(payload: JwtPayload) {
const user = await this.userService
.getUserById(payload.id)
.catch(() => {
throw new UnauthorizedException();
});
if (!user) {
throw new UnauthorizedException();
}
UserStorage.set(user);
return user;
}
<!-- Get User Object whereever needed -->
@Injectable()
class UserService {
async getUser(body: SuperInterface) {
const user = UserStorage.get();
// ... do something with the user
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment