【发布时间】:2022-03-19 03:16:19
【问题描述】:
我正在尝试使用来自 js-joda 的 LocalDate 类型作为 GraphQL 查询的参数,如下所示:
@Query(() => DataResponse)
async getData(@Args() filter: DataFilter): Promise<DataResponse> { ... }
这里是过滤器类型定义:
@ArgsType()
export class DataFilter {
@Field({ nullable: true })
@IsOptional()
date?: LocalDate;
@Field()
@Min(1)
page: number;
@Field()
@Min(1)
pageSize: number;
}
我还将LocalDate 注册为标量类型并将其添加到应用程序提供程序。
@Scalar('LocalDate', (type) => LocalDate)
export class LocalDateScalar implements CustomScalar<string, LocalDate> {
description = 'A date string, such as 2018-07-01, serialized in ISO8601 format';
parseValue(value: string): LocalDate {
return LocalDate.parse(value);
}
serialize(value: LocalDate): string {
return value.toString();
}
parseLiteral(ast: ValueNode): LocalDate {
if (ast.kind === Kind.STRING) {
return LocalDate.parse(ast.value);
}
return null;
}
}
这是我遇到的错误
[Nest] 9973 - 2022 年 2 月 16 日下午 5:33:41 错误 [ExceptionsHandler] 年 不得为空 NullPointerException:年份不得为空 在 requireNonNull (/Users/usr/my-app/node_modules/@js-joda/core/src/assert.js:33:15) 在新的 LocalDate (/Users/usr/my-app/node_modules/@js-joda/core/src/LocalDate.js:284:9) 在 TransformOperationExecutor.transform (/Users/usr/my-app/node_modules/src/TransformOperationExecutor.ts:160:22) 在 TransformOperationExecutor.transform (/Users/usr/my-app/node_modules/src/TransformOperationExecutor.ts:333:33) 在 ClassTransformer.plainToInstance (/Users/usr/my-app/node_modules/src/ClassTransformer.ts:77:21) 在 Object.plainToClass (/Users/usr/my-app/node_modules/src/index.ts:71:27) 在 ValidationPipe.transform (/Users/usr/my-app/node_modules/@nestjs/common/pipes/validation.pipe.js:51:39) 在 /Users/usr/my-app/node_modules/@nestjs/core/pipes/pipes-consumer.js:17:33 在 processTicksAndRejections (node:internal/process/task_queues:96:5)
我不确定为什么会发生这种情况,但从我设法调试的结果来看,上面定义的 LocalDateScalar 正在将值从字符串正确转换为 LocalDate,但问题是 class-transformer也在尝试转换该值,并且由于它已经转换,因此将其识别为object,这是通过无参数构造函数自动调用的,它会导致此错误。
这是调用构造函数的类转换器的行
newValue = new (targetType as any)();
有没有办法告诉类转换器忽略哪些类型?我知道@Exclude 属性,但是属性被完全排除在外,我只需要排除通过类转换器的plainToClass 方法转换的属性。还是应该以不同的方式处理整个情况?
任何建议将不胜感激。
【问题讨论】:
标签: graphql nestjs class-transformer