Back to Top

GraphQL Mutation

Updated 30 September 2022

In this blog, we will discuss the GraphQl Mutation

What is Mutation in GraphQL:

It is an operation of GraphQL by which you can insert new data or modify the existing data.

This Blog will familiarize you with the GraphQl mutation

There are some Easy steps you can follow to create a graphQL Mutation

Start your headless eCommerce
now.
Find out More
  • create this file to register your module

app/code/Webkul/GraphQlMutation/registration.php

<?php
/**
* Webkul Software.
*
* @category  Webkul
* @package   Webkul_GraphQlMutation
* @author    Webkul
* @license   https://store.webkul.com/license.html
*/
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Webkul_GraphQlMutation',
    __DIR__
);
  • To define the module name you have to create app/code/Webkul/GraphQlMutation/etc/module.xml
<?xml version="1.0"?>
<!--
/**
* Webkul Software.
*
* @category  Webkul
* @package   Webkul_GraphQlMutation
* @author    Webkul
* @license   https://store.webkul.com/license.html
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Webkul_GraphQlMutation" >
        <sequence>
            <module name="Magento_Customer"/>
            <module name="Magento_Authorization"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>
  • First, we have to define the Schema of Mutation. The schema is a container of your type hierarchy, which accepts root types in a constructor and provides methods for receiving information about your types to internal GrahpQL tools. The schema consists of two root types:
  1. Query: type is a surface of your read API. You can refer to our GraphQl query Blog Graphql query
  2. Mutation: type exposes write API by declaring all possible mutations in your app

create schema.graphqls at this path app/code/Webkul/GraphQlMutation/etc/

#GraphQl Schema for Mutation

type Mutation {
editCustomerName (customerId: Int! @doc(description: "Customer Id to load the customer Data"),
firstName: String! @doc(description: "First Name as a input"),
lastName: String! @doc(description: "Last Name as a input")):
EditCustomerName @resolver(class: "Webkul\\TestGraphQl\\Model\\Resolver\\EditCustomerName") @doc(description: "The EditCustomer name Mutation will edit the name of the customer")
}
type EditCustomerName @doc(description: "Testcustomer defines the customer name and other details") {
    firstName: String
    lastName: String
}
  • Create Resolver Model class which is defined in the schema. In this resolve method, we will edit the customer name.
<?php

/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_GraphQlMutation
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited  (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

declare(strict_types=1);

namespace Webkul\GraphQlMutation\Model\Resolver;

use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\GraphQl\Model\Query\ContextInterface;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollection;
use Magento\Customer\Model\CustomerFactory;

class EditCustomerName implements ResolverInterface
{
    

    /**
     * @inheritdoc
     */
    public function __construct(
        CustomerFactory $customerModel,
        CustomerCollection $customerCollection
    ) {
        $this->customerModel = $customerModel;
        $this->customerCollection = $customerCollection;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        try {
            /** @var ContextInterface $context */
            if (false === $context->getExtensionAttributes()->getIsCustomer()) {
                throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
            }
            $params = $args;
            $customerId = $params['customerId'];
            $first_name = $params['firstName'];
            $last_name = $params['lastName'];
            $collection = $this->customerCollection->create()
            ->addFieldToFilter('entity_id', $customerId);
            if ($collection->getSize() > 0) {
                $model = $this->customerModel->create();
                $model->load($customerId);
                $model->setFirstname($first_name);
                $model->setLastname($last_name);
                $model->save();
                return [
                    'firstName' => $model->getFirstname(),
                    'lastName' => $model->getLastname()
                ];
            } else {
                throw new GraphQlNoSuchEntityException(
                   __('Customer with customer id %1 not found',                                          $customerId));
            }
        } catch (NoSuchEntityException $exception) {
            throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
        } catch (LocalizedException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        }
    }
}

To Test The mutation first, you have to install the IDE Altair and set the Endpoint <your_base_url_to_the_pub>/graphql

Screenshot-from-2022-09-29-16-34-43-2

Please run the following command to install this module.

1 – php bin/magento setup:upgrade

2 – php bin/magento cache:flush

This will check the authentication of the customer, if you have the credentials of the customer then only you have the authorization to edit the customer

/** @var ContextInterface $context */
if (false === $context->getExtensionAttributes()->getIsCustomer()) {
   throw new GraphQlAuthorizationException(
       __('The current customer isn\'t authorized.'
   ));
}
  • Generate the customer token by graphQl mutation
mutation {
  generateCustomerToken(
   email: "<Cutomer_Email>", password: "<Customer_Password>") {
    token
  }
}

Response You will get:

{
  "data": {
    "generateCustomerToken": {
      "token": "Generated Token"
    }
  }
}

Put that customer token in the header of the GraphQL IDE

Screenshot-from-2022-09-29-13-15-13-1

You will get this pop-up set the token here

Screenshot-from-2022-09-29-13-15-47-2

After Setting up these all things you will have to perform the mutation,

Before Performing the mutation

Screenshot-from-2022-09-29-15-09-34-1

Mutation Guide

Screenshot-from-2022-09-29-15-12-45-1

After Performing Mutation

The customer name has been changed

Screenshot-from-2022-09-29-15-13-58-1

Meanwhile Please try the above example and If you have any Query then please ask in the comment section below.

Thank you!

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home