How to exclude entity field from returned by controller JSON. NestJS + Typeorm

此生再无相见时 提交于 2019-12-10 15:15:54

问题


I want to exclude password field from returned JSON. I am using NestJS and Typeorm.

The solution provided on this question doesn't work for me or in NestJS. I can post my code if needed. Any other ideas or solutions? Thanks.


回答1:


I'd suggest creating an interceptor that takes advantage of the class-transformer library:

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    call$: Observable<any>,
  ): Observable<any> {
    return call$.pipe(map(data => classToPlain(data)));
  }
}

Then, simply exclude properties using @Exclude() decorator, for example:

import { Exclude } from 'class-transformer';

export class User {
    id: number;
    email: string;

    @Exclude()
    password: string;
}



回答2:


As an addition to Kamil's answer:

Instead of creating your own interceptor, you can now use the built-in ClassSerializerInterceptor, see the serialization docs.

@UseInterceptors(ClassSerializerInterceptor)

You can use it on a controller class or its individual methods. Each entity returned by such a method will be transformed with class-transformer.


You can customize its behavior by defining @SerializeOptions() on your controller or its methods:

@SerializeOptions({
  excludePrefixes: ['_'],
  groups: ['admin']
})



回答3:


You can overwrite the toJSON method of the model like this.

@Entity()
export class User extends BaseAbstractEntity implements IUser {
  static passwordMinLength: number = 7;

  @ApiModelProperty({ example: faker.internet.email() })
  @IsEmail()
  @Column({ unique: true })
  email: string;

  @IsOptional()
  @IsString()
  @MinLength(User.passwordMinLength)
  @Exclude({ toPlainOnly: true })
  @Column({ select: false })
  password: string;

  @IsOptional()
  @IsString()
  @Exclude({ toPlainOnly: true })
  @Column({ select: false })
  passwordSalt: string;

  toJSON() {
    return classToPlain(this);
  }

  validatePassword(password: string) {
    if (!this.password || !this.passwordSalt) {
      return false;
    }
    return comparedToHashed(password, this.password, this.passwordSalt);
  }
}

By using the class-transformer method of plainToClass along with the @Exclude({ toPlainOnly: true }), the password will be excluded from the JSON response, but will be available in the model instance. I like this solution because it keeps all the model configuration in the entity.




回答4:


You can use the package https://github.com/typestack/class-transformer

You can exclude a properties using decorators and also, you can exlude properties using groups.



来源:https://stackoverflow.com/questions/50360101/how-to-exclude-entity-field-from-returned-by-controller-json-nestjs-typeorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!