我希望从返回的JSON中排除密码字段。我正在使用NestJS和Typeorm。
在这个问题上提供的解决方案不适合我,也不适用于NestJS。如果需要的话,我可以发布我的代码。还有其他的想法或解决方案吗?谢谢。
发布于 2018-05-16 13:34:29
我建议创建一个利用级变压器库的拦截器:
@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;
}发布于 2019-12-02 14:02:34
您可以像这样覆盖模型的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响应之外,但将在模型实例中可用。我喜欢这个解决方案,因为它保留了实体中的所有模型配置。
发布于 2019-01-20 13:58:56
作为对卡米尔的回答的补充
现在您可以使用内置的ClassSerializerInterceptor,而不是创建您自己的拦截器,请参阅序列化文档。
@UseInterceptors(ClassSerializerInterceptor)您可以在控制器类或其各个方法上使用它。这种方法返回的每个实体都将使用类转换器进行转换,因此会考虑到@Exclude注释:
import { Exclude } from 'class-transformer';
export class User {
/** other properties */
@Exclude()
password: string;
}您可以通过在控制器或其方法上定义@SerializeOptions()来自定义其行为:
@SerializeOptions({
excludePrefixes: ['_'],
groups: ['admin']
})例如,只向某些用户公开某些字段:
@Expose({ groups: ["admin"] })
adminInfo: string;https://stackoverflow.com/questions/50360101
复制相似问题