(A) 解决方案graphql-scalars
原答案如下。
这是graphql-scalars 库的另一种解决方案:
- 安装
npm install graphql-scalars,然后
- 导入他们的
Void 类型:https://www.graphql-scalars.dev/docs/scalars/void
(B) 使用自定义scalar 的解决方案
注意:带有void-result from mutation 的设计与"GQL best practices"
此示例是为 NodeJS Apollo 框架编写的,但很容易将实现转换为您的语言/框架
我很确定:有一个名为 graphql-void 的 NPM 包,但如果您不想添加另一个依赖项,只需复制此代码即可。
1。在你的架构中定义Void-scalar
# file: ./schema.gql
scalar Void
2。实现解析器
// 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
3。将解析器添加到 ApolloServer
将 Void 解析器添加到您的 Apollo 服务器实例的选项中:
# file: ./server.js
import { ApolloServer } from 'apollo-server-express'
import { Void } from './scalar-void'
const server = new ApolloServer({
typeDefs, // use your schema
resolvers: {
Void: Void,
// ... your resolvers
},
})
4。在架构中使用 Void 进行突变
最后,在您的架构中使用新的scalar:
# file: ./schema.gql
type Mutation{
addElement(element: ElementData): ID
removeElement(id: ID): Void
}