3

How to create custom graphql query in custom module in magento 2.

THANKS.

2 Answers 2

6

I have cerate custom module for get customer details by customer email.

Step 1 :- You Create registration.php file

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_Mohit
 */

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

Step 2 :- create etc/module.xml file

<?xml version="1.0"?>
<!--
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_Mohit
 */
-->

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Mag_Mohit" >
        <sequence>
            <module name="Magento_Customer"/>
            <module name="Magento_Authorization"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

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

type Query {
    testcustomer( email: String @doc(description: "email of the customer")): Testcustomer @resolver(class:"Mag\\Mohit\\Model\\Resolver\\Customer") @doc(description:"The testcustomer query returns information about a customer") @cache(cacheable: false)
}
type Testcustomer @doc(description: "Testcustomer defines the customer name and other details") {
    entity_id: Int
    firstname: String
    lastname: String
    email: String
    created_in: String
    created_at: String
}

Explaintion of graphqls :-

  • type Query > declares Query operations of our module.
  • testcustomer > name of our query.
  • email: String > input name (email) and type (string).
  • Test customer > defines the identity of the query, including resolver (@resolver) class, document (@doc), is the result cacheable (@cache), etc.
  • type Test customer > define the result object of the query, including their name and type.

Setp 4 :- Create Resolver Class Model/Resolver/Customer.php

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_Mohit
 */

namespace Mag\Mohit\Model\Resolver;

use Magento\Authorization\Model\UserContextInterface;
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\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Query\Resolver\Value;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Webapi\ServiceOutputProcessor;
use Magento\Framework\Api\ExtensibleDataObjectConverter;

/**
 * Customers field resolver, used for GraphQL request processing.
 */

class Customer implements ResolverInterface
{
    /**
     * @var ValueFactory
     */
    private $valueFactory;

    /**
     * @var CustomerFactory
     */
    private $customerFactory;

    /**
     * @var ServiceOutputProcessor
     */
    private $serviceOutputProcessor;

    /**
     * @var ExtensibleDataObjectConverter
     */
    private $dataObjectConverter;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    /**
     *
     * @param ValueFactory $valueFactory
     * @param CustomerFactory $customerFactory
     * @param ServiceOutputProcessor $serviceOutputProcessor
     * @param ExtensibleDataObjectConverter $dataObjectConverter
     */
    public function __construct(
        ValueFactory $valueFactory,
        CustomerFactory $customerFactory,
        ServiceOutputProcessor $serviceOutputProcessor,
        ExtensibleDataObjectConverter $dataObjectConverter,
        CustomerRepositoryInterface $customerRepository,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->valueFactory = $valueFactory;
        $this->customerFactory = $customerFactory;
        $this->serviceOutputProcessor = $serviceOutputProcessor;
        $this->dataObjectConverter = $dataObjectConverter;
        $this->customerRepository = $customerRepository;
        $this->logger = $logger;
    }

    /**
     * @param Field $field
     * @param [type] $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return array
     */
    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {

        if (!isset($args['email'])) {
            throw new GraphQlAuthorizationException(
                __(
                    'email for customer should be specified',
                    [\Magento\Customer\Model\Customer::ENTITY]
                )
            );
        }
        try {
            $data = $this->getCustomerData($args['email']);
            $result = function () use ($data) {
                return !empty($data) ? $data : [];
            };
            return $this->valueFactory->create($result);
        } catch (NoSuchEntityException $exception) {
            throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
        } catch (LocalizedException $exception) {
            throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
        }
    }

    /**
     *
     * @param int $context
     * @return array
     * @throws NoSuchEntityException|LocalizedException
     */
    private function getCustomerData($customerEmail) : array
    {
        try {
            $customerData = [];
            $customerColl = $this->customerFactory->create()->getCollection()->addFieldToFilter('email', ['eq'=>$customerEmail]);
            foreach ($customerColl as $customer) {
                array_push($customerData, $customer->getData());
            }
            return isset($customerData[0])?$customerData[0]:[];
        } catch (NoSuchEntityException $e) {
            return [];
        } catch (LocalizedException $e) {
            throw new NoSuchEntityException(__($e->getMessage()));
        }
    }
}

Explaintion :-

  • Resolver class must implement Magento\Framework\GraphQl\Query\ResolverInterface
  • "resolve" is the main method of this class, with $args as the query’s input

Setp 5 :- Final step you check output. Run this query

{
    testcustomer(email: "[email protected]") {
        entity_id
        firstname
        lastname
        email
        created_in
        created_at
    }
}

Output

enter image description here

Check More Links

How to create graphql mutation :- https://magento.stackexchange.com/a/351569/85907

How to extend/customise existing graphql query :- https://magento.stackexchange.com/a/351571/85907

THANKS.

2

-> GraphQL Custom Module get data <-

https://devdocs.magento.com/guides/v2.4/graphql/

GraphQL is a query language for the API, allowing clients to accurately identify the data needed and the server returns only the data requested. GraphQL allows clients to upload a datasheet, server actions must return the same information. The GraphQL server only needs a single endpoint and accurately responds to the data requested by the client.

Magento provides some default queries to retrieve many data. There are various modules of Magneto which use GraphQL, like CatalogGraphQL, CmsGraphQL, CustomerGraphQL, etc. Sometimes you need to get custom data from a custom module. That time you need to need a custom graphql query to get custom data.

Today we will learn how to custom module data from GraphQl in Magento 2. First, create a basic module with a custom table and also create models for it. so after completing the basic module you need to follow below steps:

Step-1 : Update module.xml file at app/code/VendoreName/ModuleName/etc and add below code.

<?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="VendoreName_ModuleName" setup_version="1.0.0"/>
        <sequence>
            <module name="Magento_GraphQl"/>
            <module name="Magento_Backend"/>
        </sequence>
</config>

Here we need to give GraphQL dependency to our custom module.

Step-2 : Create schema.graphqls file at app/code/VendoreName/ModuleName/etc and add below code.

Before creating schema.graphqls you need to check your custom table structure. My custom table structure is given below:

+--------------+-------------------+------+-----+---------+----------------+
| Field        | Type              | Null | Key | Default | Extra          |
+--------------+-------------------+------+-----+---------+----------------+
| rule_id      | int unsigned      | NO   | PRI | NULL    | auto_increment |
| customer_id  | int               | NO   | UNI | 0       |                |
| shared       | smallint unsigned | NO   | MUL | 0       |                |
| sharing_code | varchar(32)       | YES  |     | NULL    |                |
| updated_at   | timestamp         | YES  |     | NULL    |                |
+--------------+-------------------+------+-----+---------+----------------+

Now Create schema.graphqls file you need to add String data type to varchar, text, timestamp, etc column type and add Int data type to int, smallint, etc column into this file. And You need to add column description into @doc("desc").

type Query {
    getCustomData : [customdata] @resolver( class: "VendoreName\\ModuleName\\Model\\Resolver\\CustomData") @doc(description: "Get All  Banners")
}

type customdata {
    rule_id : Int  @doc(description: "Primary Id"),
    customer_id : Int  @doc(description: "Customer Id"),
    shared : Int  @doc(description: "Share Code Number"),
    sharing_code : String  @doc(description: "Share Code String"),
    updated_at : String  @doc(description: "Update Date")
}

Each module that adds to or extends from a GraphQL schema can do so by placing a schema.graphqls file in its etc directory.

Here we have created a GraphQl query. Now we need to implement an important thing @resolver( class: "VendoreName\ModuleName\Model\Resolver\CustomData") to show data while running a query.

Step-3 : Create CustomData.php file at app/code/VendoreName/ModuleName/Model/Resolver and add below code.

<?php

namespace VendoreName\ModuleName\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

class CustomData implements ResolverInterface
{
    private $customDataProvider;

    public function __construct(
        \VendoreName\ModuleName\Model\Resolver\DataProvider\CustomData $customDataProvider
    ) {
        $this->customDataProvider = $customDataProvider;
    }

    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $customData = $this->customDataProvider->getCustomData();
        return $customData;
    }
}

After that, we need to create a DataProvider file which is defined in the above __construct().

Step-4 : Create CustomData.php file at app/code/VendoreName/ModuleName/Model/Resolver/DataProvider and add below code.

<?php

namespace VendoreName\ModuleName\Model\Resolver\DataProvider;

use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;

class CustomData
{
    protected $modelFactory;

    public function __construct(
        \VendoreName\ModuleName\Model\ModelNameFactory $modelFactory
        )
    {
        $this->modelFactory  = $modelFactory;
    }

    public function getCustomData( )
    {
        try {
            $collection = $this->modelFactory->create()->getCollection();
            $CustomData = $collection->getData();

        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
        }
        return $CustomData;
    }
}

In the above file, the getCustomData() function is responsible to get data from a custom table And you need to replace your model name into __construct().

Step-5: Run Magento upgrade command after creating the above file

bin/magento setup:upgrade
bin/magento c:f

Step-6: To Run GraphQL You can use some extensions like ChromeiQL or Altair GraphQL addon. After that To check our custom query we need to set up the endpoint. It is usually coming like <magento_root_url>/graphql. first, add your base URL, and after that add /graphql like:- http://localhost/graphql. then add our custom query to the left side panel.

query customdata {
  customdata {
    rule_id
    customer_id
    shared
    sharing_code
    updated_at
  }
}

Then run and you can see your table data into the right-side panel. With the above files, we get a collection of our Custom module table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.