如何从控制器 JSON 返回的实体字段中排除。 NestJS Typeorm

新手上路,请多包涵

我想从返回的 JSON 中排除密码字段。我正在使用 NestJS 和 Typeorm。

这个问题 上提供的解决方案对我或 NestJS 都不起作用。如果需要,我可以发布我的代码。还有其他想法或解决方案吗?谢谢。

原文由 Vladyslav Moisieienkov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

我建议创建一个利用 类转换 器库的拦截器:

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

然后,只需使用 @Exclude() 装饰器排除属性,例如:

 import { Exclude } from 'class-transformer';

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

    @Exclude()
    password: string;
}

原文由 Kamil Myśliwiec 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以像这样覆盖模型的 toJSON 方法。

 @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);
  }
}

通过将 plainToClass 的类转换器方法与 @Exclude({ toPlainOnly: true }) 一起使用,密码将从 JSON 响应中排除,但在模型实例中可用。我喜欢这个解决方案,因为它保留了实体中的所有模型配置。

原文由 Francisco J Sucre G 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题