1

I'm creating Graphql for my custom module, but after setting an endpoint and writing a query for it, does not return any data.

Below are the files I have created for Graphql,

MyVendor/RMAModule/etc/schema.graphqls

type Query {
    RmaResolver (
        emailId: String @doc(description: "Email Address")
    ): RmaResolver @resolver(class:"MyVendor\\RMAModule\\Model\\Resolver\\RmaResolver") @doc(description:"Custom Module Datapassing")
}

type RmaResolver {
    rmaData: [RmaRecord] @doc(description: "RMA records")
}

type RmaRecord {
    entity_id : Int @doc(description: "Entity Id")
    order_id : Int @doc(description: "Order Id")
    customer_id : Int @doc(description: "Customer Id")
    customer_name : String @doc(description: "Customer Name")
    customer_email : String @doc(description: "Customer Email")
    delivery_status : String @doc(description: "Delivery Status")
    additional_info : String @doc(description: "Additional Info")
    rma_status : String @doc(description: "RMA Status")
    created_on : String @doc(description: "Created on")
}

MyVendor/RMAModule/Model/Resolver/RmaResolver.php

    <?php
namespace MyVendor\RMAModule\Model\Resolver;
 
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
use MyVendor\RMAModule\Model\RmaFactory;

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

    /**
     * @var RmaFactory
     */
    protected $rmaFactory;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;
 
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

     /**
     * @param ValueFactory $valueFactory     
     * @param RmaFactory $rmaFactory
     * @param CustomerRepositoryInterface $customerRepository
     * @param AccountManagementInterface $customerAccountManagement
     * @param StoreManagerInterface $storeManager
     * @param array
     */
    public function __construct(
        ValueFactory $valueFactory,
        RmaFactory $rmaFactory,
        CustomerRepositoryInterface $customerRepository,
        AccountManagementInterface $customerAccountManagement,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->valueFactory = $valueFactory;
        $this->rmaFactory = $rmaFactory;
        $this->customerRepository = $customerRepository;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->storeManager = $storeManager;
    }

     /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        try{
            $emailId = $this->getEmailId($args);
            $rmaData = $this->getRmaData($emailId);

            $result = function () use ($rmaData) {
                return !empty($rmaData) ? $rmaData : [];
            };            
            return $this->valueFactory->create($result);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        } catch (LocalizedException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        }
    }

     /**
     * @param array $args
     * @return int
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): int
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }
 
        return (int)$args['emailId'];
    }

    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    public function getRmaData(string $emailId): array
    {
        $emailNotExist = $this->emailExistOrNot($emailId);

        if($emailNotExist){
            // Guest User
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                ->addFieldToFilter("customer_email", $emailId)
                ->addFieldToFilter('customer_id', null);
        }else{
            // Customer
            $customerData = $this->customerRepository->get($emailId);
            $customerId = (int)$customerData->getId();
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                            ->addFieldToFilter("customer_id", $customerId);
        }

        $output['rmaData'] = [];
        foreach ($rmaCollection as $rmaItem) {
            // $output['rmaData'][] = [
            //     'entity_id' => $rmaItem['entity_id'],
            //     'order_id' => $rmaItem['order_id'],
            //     'customer_id' => $rmaItem['customer_id'],
            //     'customer_name' => $rmaItem['customer_name'],
            //     'customer_email' => $rmaItem['customer_email'],
            //     'delivery_status' => $rmaItem['delivery_status'],
            //     'additional_info' => $rmaItem['additional_info'],
            //     'rma_status' => $rmaItem['rma_status'],
            //     'created_on' => $rmaItem['created_on']
            // ];
            $rmaId = $rmaItem->getId();
            $output['rmaData'][$rmaId]['entity_id'] = $rmaItem['entity_id'];
            $output['rmaData'][$rmaId]['order_id'] = $rmaItem['order_id'];
            $output['rmaData'][$rmaId]['customer_id'] = $rmaItem['customer_id'];
            $output['rmaData'][$rmaId]['customer_name'] = $rmaItem['customer_name'];
            $output['rmaData'][$rmaId]['customer_email'] = $rmaItem['customer_email'];
            $output['rmaData'][$rmaId]['delivery_status'] = $rmaItem['delivery_status'];
            $output['rmaData'][$rmaId]['additional_info'] = $rmaItem['additional_info'];
            $output['rmaData'][$rmaId]['rma_status'] = $rmaItem['rma_status'];
            $output['rmaData'][$rmaId]['created_on'] = $rmaItem['created_on'];
        }
        return $output;
       
    }

    /**
     * Returns Email Id exist or not
     *
     * @return bool
     */
    public function emailExistOrNot($emailId): bool
    {
        $websiteId = (int)$this->storeManager->getWebsite()->getId();
        $isEmailNotExists = $this->customerAccountManagement->isEmailAvailable($emailId, $websiteId);
        return $isEmailNotExists;
    }
}

I have set an endpoint as http://127.0.0.1/magento243/graphql and the query is,

{
  RmaResolver(emailId: "abc@example.com") {
    rmaData{
      entity_id
      order_id
      customer_id
      customer_name
      customer_email
      delivery_status
      additional_info
      rma_status
      created_on
    }
  }
}

But the result is blank array,

{
  "data": {
    "RmaResolver": {
      "rmaData": []
    }
  }
}

I have also created an API for getting data and with the API I'm getting records. FYI defined email-id is a customer and has rma records.

Please let me know if anyone has a solution.

1 Answer 1

2

Update below files and run magetno 2 upgrade and cache clean command

MyVendor/RMAModule/etc/schema.graphqls

type Query {
    RmaResolver (
        emailId: String @doc(description: "Email Address")
    ): [RmaRecord] @resolver(class:"MyVendor\\RMAModule\\Model\\Resolver\\RmaResolver") @doc(description:"Custom Module Datapassing")
}

type RmaRecord {
    entity_id : Int @doc(description: "Entity Id")
    order_id : Int @doc(description: "Order Id")
    customer_id : Int @doc(description: "Customer Id")
    customer_name : String @doc(description: "Customer Name")
    customer_email : String @doc(description: "Customer Email")
    delivery_status : String @doc(description: "Delivery Status")
    additional_info : String @doc(description: "Additional Info")
    rma_status : String @doc(description: "RMA Status")
    created_on : String @doc(description: "Created on")
}

MyVendor/RMAModule/Model/Resolver/RmaResolver.php

<?php

namespace MyVendor\RMAModule\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
use MyVendor\RMAModule\Model\RmaFactory;

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

    /**
     * @var RmaFactory
     */
    protected $rmaFactory;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

     /**
     * @param ValueFactory $valueFactory
     * @param RmaFactory $rmaFactory
     * @param CustomerRepositoryInterface $customerRepository
     * @param AccountManagementInterface $customerAccountManagement
     * @param StoreManagerInterface $storeManager
     * @param array
     */
    public function __construct(
        ValueFactory $valueFactory,
        RmaFactory $rmaFactory,
        CustomerRepositoryInterface $customerRepository,
        AccountManagementInterface $customerAccountManagement,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->valueFactory = $valueFactory;
        $this->rmaFactory = $rmaFactory;
        $this->customerRepository = $customerRepository;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->storeManager = $storeManager;
    }

     /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        try{
            return $this->getRmaData($args);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        } catch (LocalizedException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        }
        return [];
    }

     /**
     * @param array $args
     * @return int
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): int
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }
        return (int)$args['emailId'];
    }

    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    public function getRmaData(string $emailId): array
    {
        $emailNotExist = $this->emailExistOrNot($emailId);

        if($emailNotExist){
            // Guest User
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                ->addFieldToFilter("customer_email", $emailId)
                ->addFieldToFilter('customer_id', null);
        }else{
            // Customer
            $customerData = $this->customerRepository->get($emailId);
            $customerId = (int)$customerData->getId();
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                            ->addFieldToFilter("customer_id", $customerId);
        }

        $output = [];
        foreach ($rmaCollection as $rmaItem) {
            // $output['rmaData'][] = [
            //     'entity_id' => $rmaItem['entity_id'],
            //     'order_id' => $rmaItem['order_id'],
            //     'customer_id' => $rmaItem['customer_id'],
            //     'customer_name' => $rmaItem['customer_name'],
            //     'customer_email' => $rmaItem['customer_email'],
            //     'delivery_status' => $rmaItem['delivery_status'],
            //     'additional_info' => $rmaItem['additional_info'],
            //     'rma_status' => $rmaItem['rma_status'],
            //     'created_on' => $rmaItem['created_on']
            // ];
            $rmaId = $rmaItem->getId();
            $output[$rmaId]['entity_id'] = $rmaItem['entity_id'];
            $output[$rmaId]['order_id'] = $rmaItem['order_id'];
            $output[$rmaId]['customer_id'] = $rmaItem['customer_id'];
            $output[$rmaId]['customer_name'] = $rmaItem['customer_name'];
            $output[$rmaId]['customer_email'] = $rmaItem['customer_email'];
            $output[$rmaId]['delivery_status'] = $rmaItem['delivery_status'];
            $output[$rmaId]['additional_info'] = $rmaItem['additional_info'];
            $output[$rmaId]['rma_status'] = $rmaItem['rma_status'];
            $output[$rmaId]['created_on'] = $rmaItem['created_on'];
        }
        return $output;
    }

    /**
     * Returns Email Id exist or not
     *
     * @return bool
     */
    public function emailExistOrNot($emailId): bool
    {
        $websiteId = (int)$this->storeManager->getWebsite()->getId();
        $isEmailNotExists = $this->customerAccountManagement->isEmailAvailable($emailId, $websiteId);
        return $isEmailNotExists;
    }
}

Query is:

query RmaResolver {
    RmaResolver(emailId: "abc@example.com"){
        entity_id
        order_id
        customer_id
        customer_name
        customer_email
        delivery_status
        additional_info
        rma_status
        created_on
    }
}

[Update] Check Below For Your Reference, It might help you.

app/code/VendoreName/ModuleName/etc/schema.graphqls

type Query {
    getbytype (
        type: Int @doc(description: "get Banner by type")
    ): [getbyytype] @resolver(class: "VendoreName\\ModuleName\\Model\\Resolver\\BannerType") @doc(description: "The query returns the banner belong to type id")
}

type getbyytype @doc(description: "all Attributes to show in Product Details Page") {
    banner_id : Int  @doc(description: "Banner Id")
    title : String  @doc(description: "Title")
    status : Int  @doc(description: "Status")
    image : String  @doc(description: "If image then show")
    banner_title : String  @doc(description: "Banner title")
    color_picker : String  @doc(description: "Colore Picker title")
    color_picker_bg: String  @doc(description: "Background Colore Picker title")
    banner_content : String  @doc(description: "Banner Content")
    banner_type : Int  @doc(description: "Banner Type")
    button_show : Int  @doc(description: "Button Show status")
    button_txt : String  @doc(description: "Button text")
    button_color : String  @doc(description: "Button colore")
    display_position : Int  @doc(description: "Display Position ")
    position : Int  @doc(description: "Position")
}

app/code/VendoreName/ModuleName/Model/Resolver/BannerType.php

<?php

namespace VendoreName\ModuleName\Model\Resolver;

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

class BannerType implements ResolverInterface
{
    private $bannertypeDataProvider;

    /**
     * @param DataProvider\BannerType $bannertypeDataProvider
     */
    public function __construct(
        \VendoreName\ModuleName\Model\Resolver\DataProvider\BannerType $bannertypeDataProvider
    ) {
        $this->bannertypeDataProvider = $bannertypeDataProvider;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        //by Type
        $type = $this->getType($args);
        $bannerData = $this->bannertypeDataProvider->getByType($type);
        return $bannerData;
    }

    private function getType(array $args)
    {
        if (!isset($args['type'])) {
            throw new GraphQlInputException(__('"Type should be specified'));
        }
        return $args['type'];
    }
}

app/code/VendoreName/ModuleName/Model/Resolver/DataProvider/BannerType.php

<?php

namespace VendoreName\ModuleName\Model\Resolver\DataProvider;

class BannerType extends \Magento\Framework\View\Element\Template
{
    protected $_bannerTypeData;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \VendoreName\ModuleName\Model\BannerFactory $bannerTypeData,
        array $data = []
    ) {
        $this->_bannerTypeData = $bannerTypeData;
        parent::__construct($context, $data);
    }

    /**
     * @params int $id
     * this function return all the word of the day by id
     **/
    public function getByType($type)
    {
        $atr_data = $this->_bannerTypeData->create()->getCollection();
        $atr_data->addFieldToFilter('display_position', $type);
        $attributes_data = [];
        $x = 0;
        foreach ($atr_data as $attribute) {
            $attributes_data[$x]['banner_id'] = $attribute->getId();
            $attributes_data[$x]['title'] = $attribute->getTitle();
            $attributes_data[$x]['status'] = $attribute->getStatus();
            $attributes_data[$x]['image'] = $attribute->getImage();
            $attributes_data[$x]['banner_title'] = $attribute->getBannerTitle();
            $attributes_data[$x]['color_picker'] = $attribute->getColorPicker();
            $attributes_data[$x]['color_picker_bg'] = $attribute->getColorPickerBg();
            $attributes_data[$x]['banner_content'] = $attribute->getBannerContent();
            $attributes_data[$x]['button_show'] = $attribute->getButtonShow();
            $attributes_data[$x]['button_txt'] = $attribute->getButtonTxt();
            $attributes_data[$x]['button_color'] = $attribute->getButtonColor();
            $attributes_data[$x]['banner_type'] = $attribute->getBannerType();
            $attributes_data[$x]['display_position'] = $attribute->getDisplayPosition();
            $attributes_data[$x]['position'] = $attribute->getPosition();
            $x++;
        }
        return $attributes_data;
    }
}

Query is:

query getbytype {
  getbytype(type: 2) {
    banner_id
    title
    status
    image
    banner_title
    color_picker
    color_picker_bg
    banner_content
    banner_type
    button_show
    button_txt
    button_color
    display_position
    position
  }
}

Note: Must be run upgrade and cache clean command.

Please try with static data and you can use echo and print_r() and check into the network tab to inspect (F12) to see data and log

MyVendor/RMAModule/Model/Resolver/RmaResolver.php

Before changes

/**
 * @param array $args
 * @return int
 * @throws GraphQlInputException
 */
public function getEmailId(array $args): int
{
    if (!isset($args['emailId'])) {
        throw new GraphQlInputException(__('EmailId should be specified'));
    }
    return (int)$args['emailId'];
}

After Changes which is working

/**
     * @param array $args
     * @return string
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): string
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }
 
        return (string)$args['emailId'];
    }
15
  • Thank you for your response, I have tried that as well I have updated the RmaResolver.php file in question.
    – Mohit Rane
    Dec 27, 2021 at 10:17
  • I have updated the resolve() and getRmaData() but still it shows blank
    – Mohit Rane
    Dec 27, 2021 at 10:45
  • Please check the updated answer.
    – Msquare
    Dec 27, 2021 at 10:49
  • okay i will try this
    – Mohit Rane
    Dec 27, 2021 at 10:54
  • still data is blank.
    – Mohit Rane
    Dec 27, 2021 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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