#User-Decorator with typeorm
14 messages · Page 1 of 1 (latest)
How/where do you want to use this decorator?
Controller, as like ```ts
async getXYZ(@User() user: UserEntity){
// user has the user entity out of database, in user decorator i get the userid that is in the bearer auth token and then get the user out of database
}
Why not use a pipe to hydrate the userId to be a full entity? A decorator itself can't (and shouldn't in my opinion) run async commands to modify the parameter itself. Nest has a built in way to do that already
could you give me an example?
@Injectbale()
export class UserHydrationPipe implements PipeTransform<string, UserType> {
// this could be @InjectRepository(User), @InjectModel(User.name), UserService, whatever
constructor(private readonly userDbAccess: UserDbAccessor) {}
async transform(id: string, metadata: ArgumentMetadata) {
const user = await this.useDbAccess.get({ where: { id } });
return user;
}
}
Then you can use it like
@Get('some/path/')
getSomtehingWithUser(@User(UserHydrationPipe) user: UserEntity) {
return user;
}
"Hydration" is taking a single value, like an id, and returning an object based on it for further use in the route
oh okay good to know :)
I would use the@User decorator to get id from the header, like you are now, and then Nest will pass that value to the pipe, because that's how pipes work
OHHH now i get it, so the @User() is my user decorator where i get the userid from the header and the hydrationpipe is where i get the user then
Yes, it's a two step process, but everything has its place to function
okay that sounds good, thanks :D