Mutations
In version 4 of Drupal GraphQL Mutations
work a lot more similar to queries than they do in 3.x. Mutations are called using also Data producers which we already looked at.
Let's make a mutation that creates a new article. In this case it takes a data parameter that can have a title
and a description
in order to set these fields when creating the new article if they have been provided.
Similar to queries we can start by adding the necessary schema information, not only to register our new mutation but also provide type safety on all parameters as well. This mutation will return the newly created "Article".
The code with all the demo queries and mutations in these docs can be found in the same graphql_composable
example module.
Add the schema declaration
Adapt your base schema file to something like this where we include a new type called Mutation
and we also create a new input called ArticleInput
which we will use as the type for our mutation argument.
And now in our .extends.graphqls
file we will extend the Mutation type to add our new mutation. This is so that in the future other modules can also themselves extend this type with new mutations keeping things organized.
We can now see we have a Mutation called createArticle
which takes a data parameter, and because GraphQL is heavily typed we know everything we can and must include in the new Article (ArticleInput
) like the title which is mandatory in this case.
Implement the custom data producer (mutation)
We now need to implement the actual mutation, in the file src/Plugin/GraphQL/DataProducer
we include the following file CreateArticle.php
:
Important note
One thing to notice when creating mutations like this is that Access checking needs to be done in the mutation, for queries this usually is done in the data producer directly (e.g. entity_load
has access checking built-in) but because we are programmatically creating things we need to check the user actually has access to do the operation.
Calling the mutation
To add the resolvers for the createArticle
mutation we go to our schema implementation and call the created data producer create_article
inside the registerResolvers
method.
This mutation can now be called like this :
and should return something like :
Validating mutations
Now that we have our mutation in place one way we can improve this is by adding some validation so that if someone is not to create an article they get a nice error back (technically in Drupal these are called Violations) so that it can be printed to the user in whichever app this is called. In the next chapter we will look at how we can improve this code to add some validation to it.
Last updated