我不知道我错过了什么,但当我调试时,突变或查询的输入始终为空,似乎输入是空对象
这是我的代码:
解析器
@Query(() => String)
async testMutation(@Args('args') args: UpvotePostInput) {
return args.postId;
}
Run Code Online (Sandbox Code Playgroud)
数据传输工具
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class UpvotePostInput {
@Field(() => String)
postId: string;
}
Run Code Online (Sandbox Code Playgroud)
错误
{
"errors": [
{
"message": "Cannot return null for non-nullable field Query.testMutation.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"testMutation"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Cannot return null for non-nullable field Query.testMutation.",
" at completeValue (/....js:559:13)",
" at /.....xecute.js:469:16",
" at processTicksAndRejections (internal/process/task_queues.js:97:5)",
" at async Promise.all (index 0)"
]
}
}
}
],
"data": null
}
Run Code Online (Sandbox Code Playgroud)
解决方案是向属性添加@IsNotEmpty()或装饰器:@IsOptional()
@InputType()
export class UpdateCarInput extends PartialType(CreateCarInput) {
@Field(() => Int)
@IsNotEmpty()
id: number;
}
Run Code Online (Sandbox Code Playgroud)
奇怪,但这解决了问题。
我研究了 Nestjs 的这种行为,发现当使用全局验证管道并将白名单属性设置为 true 时会发生这种情况。我测试了这个全局验证管道
app.useGlobalPipes(
new ValidationPipe({
// whitelist: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
}),
);
Run Code Online (Sandbox Code Playgroud)
对于这个解析器方法
@Mutation()
createPost(@Args('input') input: CreatePostInput) {
return this.postsService.create(input);
}
Run Code Online (Sandbox Code Playgroud)
CreatePostInput类是使用 Nestjs graphql 模式第一种方法生成的
//graphql.ts file
export class CreatePostInput {
title: string;
authorId: number;
}
Run Code Online (Sandbox Code Playgroud)
Nestjs-cli.json 文件配置为使用@nestjs/graphql插件
"compilerOptions": {
"plugins": [
{
"name": "@nestjs/graphql",
"options": {
"introspectComments": true
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
输入对象不是空对象
| 归档时间: |
|
| 查看次数: |
2672 次 |
| 最近记录: |