本文介绍了如何从控制器JSON返回的值中排除实体字段. NestJS + Typeorm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从返回的JSON中排除密码字段.我正在使用NestJS和Typeorm.
I want to exclude password field from returned JSON. I am using NestJS and Typeorm.
不适用于我或NestJS.如果需要,我可以发布我的代码.还有其他想法或解决方案吗?谢谢.
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.
推荐答案
我建议创建一个利用类转换器库:
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)));
}
}
然后,只需使用@Exclude()
装饰器排除属性,例如:
Then, simply exclude properties using @Exclude()
decorator, for example:
import { Exclude } from 'class-transformer';
export class User {
id: number;
email: string;
@Exclude()
password: string;
}
这篇关于如何从控制器JSON返回的值中排除实体字段. NestJS + Typeorm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!