Implementing mutations for content creation/updatefor Drupal 8 , 9 , 10 , and 11

Last updated :  

In a headless Drupal setup, one of the core strengths of GraphQL lies in its ability to perform complex data operations. Mutations, a key feature of GraphQL, enable you to handle content creation, updates, and deletions seamlessly through a single interface. This lesson will guide you through developing mutations for creating and updating content in Drupal.

Understanding GraphQL Mutations

While queries in GraphQL are used to fetch data, mutations allow you to modify data on the server side. Similar to queries, mutations follow a specific structure defined by your schema, which describes what mutations can be performed and what data is required to do so.

Prerequisites

Before we begin, ensure you have a functioning GraphQL setup in your Drupal environment. Configuration of appropriate schema definitions and basic understanding of GraphiQL for testing are also necessary.

Creating a Mutation in GraphQL

Implementing mutations involves defining them in your schema and developing resolvers that process the data operations. Follow the steps below to implement a content creation or update mutation.

Step 1: Define Mutation Types in the Schema

To start, enhance your graphql.schema.yml file by adding mutation types. Here’s an example for creating a new node:


    mutationFields:
      createArticle:
        type: result
        arguments:
          title: String!
          body: String!
        resolve: '@@createArticleResolver'
    

Here, createArticle specifies the mutation name. It takes title and body as arguments, with a mandatory specifier (!), and references a resolver for processing the mutation.

Step 2: Implement the Resolver

The resolver translates the mutation request into actionable code that creates or updates content. Here’s a sample implementation for the createArticleResolver:


    <?php

    namespace Drupal\custom_graphql\GraphQL\Resolvers;

    use Drupal\node\Entity\Node;
    use Drupal\Core\Session\AccountProxyInterface;
    use Drupal\Core\Messenger\MessengerInterface;

    class CreateArticleResolver {
      
        protected $currentUser;
        protected $messenger;

        public function __construct(AccountProxyInterface $currentUser, MessengerInterface $messenger) {
            $this->currentUser = $currentUser;
            $this->messenger = $messenger;
        }

        public function __invoke($root, $args, $context, $info) {
            // Validate user permissions (assuming 'create article content' permission existence).
            if (!$this->currentUser->hasPermission('create article content')) {
                throw new \Exception('Unauthorized: Cannot create content.');
            }

            // Create a new node of type article with the provided title and body.
            $node = Node::create([
                'type' => 'article',
                'title' => $args['title'],
                'body' => [
                    'value' => $args['body'],
                    'format' => 'basic_html',
                ],
                'uid' => $this->currentUser->id(),
                'status' => 1, // Publish status
            ]);
            $node->save();

            // Return a result indicating success.
            return ['status' => 'success', 'nid' => $node->id()];
        }
    }
    

Step 3: Testing Your Mutation

With the schema and resolver in place, test your mutation using the GraphiQL interface:


    mutation {
      createArticle(title: "New GraphQL Article", body: "This is the content using GraphQL mutations.") {
        status
        nid
      }
    }
    

Execute this mutation and verify the operation by checking for the node with the returned node ID.

Handling Updates with Mutations

Updating an entity is a similar process. Define an update mutation, and in the resolver, load the node using the ID, modify fields, and save changes. Example schema entry:


    mutationFields:
      updateArticle:
        type: result
        arguments:
          nid: Int!
          title: String
          body: String
        resolve: '@@updateArticleResolver'
    

This setup allows modifications of the article title and body, depending on the arguments supplied.

Best Practices for Mutations

  • Validation: Always validate inputs to prevent incorrect data entry.
  • Permission Checking: Check user permissions to ensure secure data operations.
  • Comprehensive Testing: Ensure thorough testing of the mutation operations to detect issues early.

Conclusion

Implementing mutations in GraphQL for content creation and updates enriches your headless Drupal architecture, facilitating dynamic, real-time content management. By integrating these operations, your application gains versatility and responsiveness.

Preview of Next Lesson

The forthcoming lesson will delve into Securing GraphQL Endpoints with Tokens. You'll learn strategies for securing your GraphQL API, ensuring data protection and controlled access. Stay engaged to fortify the security of your headless application!