#User-Decorator with typeorm

14 messages · Page 1 of 1 (latest)

silver vessel
#

Hey, how can i create a user decorator? I know like the createCustomDecorator thing but how do i access the typeorm database? In services i can do ```ts
constructor(private userRepository: Repository<UserEntity>) {}


but in the decorator i cannot do that so how do i access the repository to the user?
keen rock
#

How/where do you want to use this decorator?

silver vessel
#

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
}

keen rock
#

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

silver vessel
#

could you give me an example?

keen rock
#
@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;
}
silver vessel
#

What exactly is "Hydration"?

#

and can i access the request header in the pipe?

keen rock
silver vessel
#

oh okay good to know :)

keen rock
silver vessel
#

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

keen rock
#

Yes, it's a two step process, but everything has its place to function

silver vessel
#

okay that sounds good, thanks :D