Created
April 8, 2023 08:01
-
-
Save islahh/223e6f2dd64fb11d3ccf2b55e2811ee9 to your computer and use it in GitHub Desktop.
Create async local storage using node JS async_hooks in NestJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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