(A) Solution with graphql-scalars
The original answer is below.
Here is another one solution with graphql-scalars
library:
- install
npm install graphql-scalars
and then
- import their
Void
type: https://www.graphql-scalars.dev/docs/scalars/void
(B) Solution with a custom scalar
Note: design with void
-result from mutations goes against "GQL best practices"
This example was written for NodeJS Apollo Framework, but it is pretty easy to convert the implementation for your language/framework
I'm pretty sure: there is an NPM-package named graphql-void
but if you don't want to add another one dependency just copy this code.
1. define Void
-scalar in your schema
# file: ./schema.gql
scalar Void
2. implement resolver
// 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. add the resolver to ApolloServer
Add the Void
resolver to the options of your instance of Apollo Server:
# 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. use Void
for your mutations in the schema
Finally, use the new scalar
in your schema:
# file: ./schema.gql
type Mutation{
addElement(element: ElementData): ID
removeElement(id: ID): Void
}