#DTO filter our properties

7 messages · Page 1 of 1 (latest)

bronze marlin
#

hi, is there a way to force the response from typeorm to only return the defined DTO type?
example of a service mehod:

async findAdministrator() :Promise<UserDto> {
    return await this.userRepository.findOne({order: { id: 'DESC' }});
  }

should only return the defined UserDto properties:

export class UserDto implements Partial<User> {
  @Column({
    type: 'varchar',
    unique: true,
    length: 320,
  })
  username: string;

  @Column({
    type: 'varchar',
    length: 320,
    nullable: true,
  })
  name: string;

  @Column({ type: 'text', nullable: true })
  avatar?: string;
}

but its returning all properties:

{"created_at":"2023-02-09T14:54:24.854Z","updated_at":"2023-02-09T14:54:24.854Z","id":"k9YQDRUaGht6G5m5pBTIShj9PrQgr-LzH7_y","realm":null,"username":"admin","email":"admin@admin.com","name":"","emailVerified":true,"verificationToken":"s1XkSRtFvr-Djx4g5gXC6","roles":["registered"],"avatar":"/files/get/g--T3d1Z8lShc7xcUsgaPeiWfIIAAuhIE-qk.jpeg"}
bronze marlin
#

got it!

@UseInterceptors(ClassSerializerInterceptor)

in the controller did the trick! ^^

along with
@Exclude
and @Expose

zinc dove
honest path
#

You can still choose the columns you need and remove the Partial from UserDto

bronze marlin
honest path
# bronze marlin How?

Well first idk if it's intended but you need a param to make a findOne, also since you have only one result i don't get the order by id. Anyway you can do that :

async findAdministrator(param:Paramtype) :Promise<UserDto|null> {
    return await this.userRepository.findOne({
      select: { username: true, name: true, avatar: true },
      order: { id: 'DESC' },
      where : { param : param }
    });
  }

or with querybuilder

async findAdministrator(param:Paramtype) :Promise<UserDto|null> {
return await this.userRepository
      .createQueryBuilder('user')
      .select('user.username, user.name, user.avatar')
      .where('user.param = :param', { param })
      .orderBy('user.id', 'DESC')
      .getOne();  
}

Having UserDto as Partial<User> means it can have any property of User, otherwise you would get a type error. Also it's better to take only the columns you actually need.

Beware that findOne can also return null (if there's no result), so you have to handle it if you want to only return a Promise<UserDto>