How to get custom module data into GraphQL Magento 2

Written by Mahesh Makwana

Nov 28, 2020

How to get custom module data into GraphQL Magento 2

GraphQL Magento 2 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 complete 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. we have create GraphQL 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 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;

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 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 must be 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.

I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP