Mutation in GRAPHQL

In the world of GraphQL, queries and mutations play distinct but complementary roles.Specifically, While GraphQL queries are designed to perform read operations, mutations handle the task of modifying data. Essentially, a mutation allows you to create, update, or delete objects and fields, functioning similarly to POST, PUT, and DELETE requests in REST terminology. Moreover, Understanding the structure and function of mutations is crucial for effective data manipulation and application management. Therefore, In this context, let’s delve into the components that make up a Mutation in GRAPHQL and see how they contribute to its functionality.

Structure of a mutation

Mutations consist of several key elements:

  • First, you need the keyword ‘mutation.
  • An operation name for your local implementation. Consequently, this name is required if you include variables. On the other hand, it is optional.
  • The mutation name
  • The input object or attributes.In particular, Most mutations require an input object that contains data or individual attributes for the application server to process. However, on the other hand, some mutations, such as createEmptyCart, do not require an input object. In this particular case, therefore, the authorization token passed with the request provides the needed context.
  • The output object, which specifies which data the mutation returns.

Example of mutation graphql

Here in this example, we are, indeed, adding data to the database using a GraphQL mutation.

Step 1 :- You Create registration.php file

<?php
/**
 * @author KPYXAL
 * @copyright Copyright (c) 2023
 * @package Kpyxal_MutationGraphql
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Kpyxal_MutationGraphql',
    __DIR__
);

Step 2 :- create etc/module.xml file

<?xml version="1.0"?>
<!--
/**
 * @author KPYXAL
 * @copyright Copyright (c) 2023
 * @package Kpyxal_MutationGraphql
 */
-->

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Kpyxal_MutationGraphql" setup_version="2.0.0">
        <sequence>
            <module name="Magento_Backend"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

Step 3 :- GraphQL queries are declared under etc/schema.graphqls

type Mutation {
    dataFormSubmit(input: FormInput!): FormOutput @resolver(class: "\\Kpyxal\\MutationGraphql\\Model\\Resolver\\FormDataSave") @doc(description:"Contact us form")
}

input FormInput {
    name: String @doc(description: "Get Name")
    number: String @doc(description: "Get Number")
    email: String @doc(description: "Get Email")
    password: String @doc(description: "Get Password")
    gender: Int @doc(description: "Get Gender")
    bdate: String @doc(description: "Get Birth Date")
}

type FormOutput {
   success_message: String @doc(description: "Success Message")
}

Explanation of graphql :-

  • type Mutation > declares Mutation operations of our module.
  • dataFormSubmit > name of our Mutation.
  • FormInput > it is input value and type.
  • FormOutput > declares output message.

Step 4 :- Create Resolver Class Model/Resolver/FormDataSave.php

<?php

namespace Kpyxal\MutationGraphql\Model\Resolver;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Kpyxal\MutationGraphql\Api\TestRepositoryInterface;
use Kpyxal\MutationGraphql\Api\Data\TestInterface;


class FormDataSave implements ResolverInterface
{
    private $contactusDataProvider;

    /**
     * @param
     */
    public function __construct(
        TestRepositoryInterface $testRepository,
        TestInterface $testInterface
    ) {
        $this->_testRepository=$testRepository;
        $this->_testModel = $testInterface;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {

        $name = $args['input']['name'];
        $number = $args['input']['number'];
        $email = $args['input']['email'];
        $password = $args['input']['password'];
        $gender = $args['input']['gender'];
        $bdate = $args['input']['bdate'];

        $this->_testModel->setName($name);
        $this->_testModel->setNumber($number);
        $this->_testModel->setEmail($email);
        $this->_testModel->setPassword($password);
        $this->_testModel->setGender($gender);
        $this->_testModel->setBdate($bdate); 
        $thanks_message = [];

        try {
            $this->_testRepository->save($this->_testModel);
            $thanks_message['success_message']="Successfully Added";
        } catch (CouldNotSaveException $e) {
            $thanks_message['success_message']="Something went wrong.";
        }
        return $thanks_message;
    }
}

Here in above resolver file we used:-


Kpyxal\MutationGraphql\Api\TestRepositoryInterface;
Kpyxal\MutationGraphql\Api\Data\TestInterface;

Additionally, the repository and interface file are designed to save fields such as email, name, and number.
Step 6 :- Final step you check output. Run this query

mutation {
    contactusFormSubmit(
        input:{
            name: "KPYXAL"
            number: "+123456798"
            email: "TEST@TEST.COM"
            password: "pass@123"
            gender: "1"
            bdate: "28/08/2222"       
        }
    ){
        success_message
    }
}

To sum up, mutations in GraphQL are essential for altering data within your application. They not only allow for the creation, update, or deletion of objects but also offer flexibility through various elements such as operation names and input objects. While mutations function akin to POST, PUT, and DELETE requests in REST, their integration with GraphQL’s robust query language provides a powerful toolset for managing data efficiently. As we continue to explore GraphQL, ultimately, understanding these components will help, significantly, in harnessing the full potential of this dynamic query language.
Happy Coding ..! 😉

Check more blogs like this: