问题描述
我无法公开对象数组.即使我在 UserDto
I am not able to expose an array of objects.The Followers array is not getting exposed, even though I exposed in the UserDto
这是我得到的,
{
"id": "5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481",
"userName": "jdbfjl",
"email": "[email protected]",
"bio": "Duuude",
"avatar": "sjldflaeulajsnlnaefb",
"followerCount": 0,
"followeeCount": 0,
"verified": false,
"followers": [
{},
{},
{}
],
"followees": [
{}
]
}
和预期的一样
{
"id": "5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481",
"createdAt": "2021-08-11T11:07:11.688Z",
"updatedAt": "2021-08-11T11:07:11.688Z",
"userName": "ashdviah",
"email": "[email protected]",
"bio": "I am Handsome",
"avatar": "sjldflaeulajsnlnaefb",
"followerCount": 0,
"followeeCount": 0,
"verified": false,
"followers": [
{
"id": "db1d30c6-5607-4d87-8838-69f906c3c44e",
"createdAt": "2021-08-11T11:09:33.018Z",
"updatedAt": "2021-08-11T11:09:33.018Z"
},
{
"id": "31492cd6-7c56-48f6-aff3-792a980b5100",
"createdAt": "2021-08-11T11:11:01.288Z",
"updatedAt": "2021-08-11T11:11:01.288Z"
},
],
"followees": [
{
"id": "ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1",
"createdAt": "2021-08-11T12:55:18.139Z",
"updatedAt": "2021-08-11T12:55:18.139Z"
}
]
}
当我没有为该路由指定拦截器时,我得到了这个输出......但事实证明我正在用它公开密码条目......
I am getting this output when I am not specifying interceptor to that route... But it turns out that I am exposing password entry with it...
我目前的方法是这样的:它没有按预期工作......我在这里错过了什么?
my current approach is something like this : which is not working as expected... what am i missing here ?
class mock {
@Expose() id : string;
@Expose() createdAt : Date;
@Expose() updatedAt : Date;
}
export class UserDto {
@Expose()
id : string;
@Expose()
userName : string;
@Expose()
email : string;
@Expose()
bio : string;
@Expose()
avatar : string;
@Expose()
followerCount : number;
@Expose()
followeeCount : number;
@Expose()
verified : boolean;
@Expose()
followers : Array<mock>;
@Expose()
followees : Array<mock>;
}
转换是由我在控制器使用的一个拦截器完成的.
And transform is getting done by one interceptor that I used at the controller.
用法:@Serialize(UserDto)
装饰器
export function Serialize(dto: ClassConstructor) {
return UseInterceptors(new Serializeinterceptor(dto));
}
export class Serializeinterceptor implements NestInterceptor {
constructor(private dto: any) {}
intercept(context: ExecutionContext, handler: CallHandler) {
return handler.handle().pipe(
map((data: any) => {
return plainToClass(this.dto, data, {
excludeExtraneousValues: true,
});
}),
);
}
}
推荐答案
对于不是基元的类型(即类),您需要添加 @Type(() => ClassType)
装饰器,这样 class-transformer 就可以知道它应该对非原始对象做什么.在这种情况下,您需要 @Type(() => mock)
.
For types that are not primitives (i.e. classes) you need to add the @Type(() => ClassType)
decorator, so that class-transformer can know what it's supposed to do about the non-primitive. In this case, you need @Type(() => mock)
.
这也是必要的根据他们的文档,对于任何数组.
This is also necessary according to their docs, for any arrays.
这篇关于使用类转换器公开对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!