Mutation in GRAPHQL

profile_img
admin

February 20, 2023

Category

blog_left_top_img

While GraphQL queries perform read operations, mutations change the data. A mutation can create, update, or delete objects and fields. In REST terminology, queries operate like GET requests, while mutations are similar to POSTPUT, and DELETE.

Structure of a mutation

A mutation contains the following elements:

  • The keyword mutation
  • An operation name for your local implementation. This name is required if you include variables. Otherwise, it is optional.
  • The mutation name
  • The input object or attributes. Most mutations require an input object that contains data or individual attributes for the application server to process. However, some mutations, such as createEmptyCart, do not require an input object. In this particular case, 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 adding data in database using 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;

repository and interface file to save fields like email,name,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
    }
}


Happy Coding ..! 😉