我有几个Graphql查询和突变,现在我正在尝试实现删除变异而不返回任何数据:
type Mutation{
addElement(element:ElementData): ID
removeElement(id:ID): ¿?
}
Run Code Online (Sandbox Code Playgroud)
但是,似乎需要删除操作的返回值.有没有办法在graphql中执行"空"响应?我想避免像可能的情况那样返回布尔值或状态标志.
我不确定Graphql删除操作的最佳实践是什么
Loc*_*0_0 24
在此问题之后,您无法返回任何内容.
您可以定义可以为空的返回类型,例如
type Mutation {
addElement(element: ElementData): ID
removeElement(id: ID): Boolean
}Run Code Online (Sandbox Code Playgroud)
但我建议你返回已删除元素的id.
因为如果您想使用缓存存储,则必须在删除突变正向传递时更新存储.
max*_*kov 20
scalar注意:带有
void-result from mutations 的设计与“GQL 最佳实践”背道而驰
这个例子是为 NodeJS Apollo 框架编写的,但是很容易转换你的语言/框架的实现
我很确定:有一个名为 NPM 的包,graphql-void但如果您不想添加另一个依赖项,只需复制此代码。
Void在你的模式中定义-scalar# file: ./schema.gql
scalar Void
Run Code Online (Sandbox Code Playgroud)
# file: ./schema.gql
scalar Void
Run Code Online (Sandbox Code Playgroud)
将Void解析器添加到 Apollo Server 实例的选项中:
// file ./scalar-void.js
import { GraphQLScalarType } from 'graphql'
const Void = new GraphQLScalarType({
name: 'Void',
description: 'Represents NULL values',
serialize() {
return null
},
parseValue() {
return null
},
parseLiteral() {
return null
}
})
export Void
Run Code Online (Sandbox Code Playgroud)
Void用于您在架构中的更改最后,scalar在您的架构中使用 new :
# file: ./schema.gql
type Mutation{
addElement(element: ElementData): ID
removeElement(id: ID): Void
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 TypeScript 和graphql-codegen:
在 GraphQL 架构中:
scalar Void
type Mutation {
removeElement(id: ID): Void
}
Run Code Online (Sandbox Code Playgroud)
在解析器的代码生成配置中:
scalar Void
type Mutation {
removeElement(id: ID): Void
}
Run Code Online (Sandbox Code Playgroud)
使用此配置,TypeScript 将确保removeElement突变解析器不会返回任何内容。并且突变的返回值将始终null在 GraphQL 端。
| 归档时间: |
|
| 查看次数: |
13704 次 |
| 最近记录: |