4

How to create custom GraphQl to Access Customer Data?

3
  • Which type of data you want to access? Nov 5, 2019 at 4:38
  • i have to access customer data using custom query Nov 6, 2019 at 9:06
  • Check this link bit.ly/31pnLai to know the List of GraphQL Queries and Mutations for Magento 2
    – MK Patel
    Oct 13, 2020 at 9:34

2 Answers 2

4

There is already an in-built GraphQl query to retrieve customer data. You can get core Magento customer data via below query.

 {
  customer {
    firstname
    lastname
    suffix
    email
    id
    addresses {
      firstname
      lastname
      street
      city
      region {
        region_code
        region
        region_id
      }
      postcode
      country_id
      telephone
    }
  }
}

The above GraphQl request will return a response shown as below.

{
  "data": {
    "customer": {
      "firstname": "John",
      "lastname": "Doe",
      "suffix": null,
      "email": "[email protected]",
      "id": 3,
      "addresses": [
       {
         "firstname": "John",
         "lastname": "Doe",
         "street": [
           "123 Elm Street"
         ],
         "city": "Anytown",
         "region": {
           "region_code": "MI",
           "region": "Michigan",
           "region_id": 33
         }
         "postcode": "78758",
         "country_id": "US",
         "telephone": "512 555-1212"
        }
      ]
    }
  }
}

Refer the developer documents for more information. https://devdocs.magento.com/guides/v2.3/graphql/queries/customer.html


If you want to return your custom customer attributes via GraphQl, instead of writing a new query, you can enhance the existing customer GraphQl query.

  1. Assume you want to append a new customer attribute 'occupation' to the existing customer query. First you need to add this information in your schema.graphqls file.

app/code/YourNamespace/YourModuleGraphQl/etc/schema.graphqls

type Customer {
    occupation: String @resolver(class: "YourNamespace\\YourModuleGraphQl\\Model\\Resolver\\Customer\\Occupation")
}

'String' is the output data type when you request occupation parameter in customer query.

  1. Now create your resolver class to prepare the data for this custom attribute.

app/code/YourNamespace/YourModuleGraphQl/Model/Resolver/Customer/Occupation.php

 <?php

    declare(strict_types=1);

    namespace YourNamespace\YourModuleGraphQl\Model\Resolver\Customer;

    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;

    class Occupation implements ResolverInterface
    {

        protected $storeManager;

        // You can inject relevant classes in this constructor function.
        public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager
        )
        {
            $this->storeManager = $storeManager;
        }

        // This is the function which will get invoked when we request 'occupation' info in the graphql query 
        public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
        {
            if (!isset($value['model'])) {
                throw new LocalizedException(__('"model" value should be specified'));
            }
            $output = [];
            $customer = $value['model'];
            $customerId = (int)$customer->getId();

            // Get the custom attribute info of the customer.
            $occupation = $this->getCustomerOccupationInfo($customerId);
            $output[
                    'occupation' => $occupation;
                ];
            return $output;
        }

        private function getCustomerOccupationInfo($customerId)
        {
            // Get the value of customer's occupation attribute and return it.
            return 'Teacher';
        }
    }
  1. Run below commands.

bin/magento setup:upgrade

rm -rf generated/

bin/magento c:f

  1. Below is an example of the customer query, which implies how you can call your 'occupation' attribute inside customer query.
{
      customer {
        firstname
        lastname
        suffix
        email
        id
        occupation
        }
    }
3

Step 1: Register new module File path: /app/code/Custom/CustomGraphQl/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Custom_CustomGraphQl’,
__DIR__
);
?>

Step 2: Create a module.xml file

<?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=”Custom_CustomGraphQl” >
<sequence>
<module name=”Magento_Customer”/>
<module name=”Magento_Authorization”/>
<module name=”Magento_GraphQl”/>
</sequence>
</module>
</config>

Step 3: Define schema

    #Magento Customer GraphQl Schema
type Query {
testcustomer(
email: String @doc(description: “Id of the customer”)
): Testcustomer @resolver(class: “Custom\\CustomGraphQl\\Model\\Resolver\\Customer”) @doc(description:
“The testcustomer query returns information about a customer”)
}
type Testcustomer @doc(description: “Testcustomer defines the customer name and other details”) {
entity_id: Int
 firstname: String
 lastname: String
email: String
}

Step 4: Create resolver model class for schema

<?php
declare(strict_types=1);
namespace Custom\CustomGraphQl\Model\Resolver;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Custom\CustomGraphQl\Model\Resolver\Customer\CustomerDataProvider;
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;
class Customer implements ResolverInterface
{
private $valueFactory;
private $customerFactory;
 private $serviceOutputProcessor;
private $dataObjectConverter;
private $logger;
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;
}
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(__($e->getMessage()));
}
}

private function getCustomerData($customerId) : array
{
try {
 $customerData = [];
$customerColl = $this->customerFactory->create()->getCollection()
>addFieldToFilter(“email”, [“eq”=>$customerId]);
 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()));
 }
 }
}

Step 5: Install module

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy -f

php bin/magento cache:flush

Step 6: Check the response

You can check your GraphQL query and response by installing a chrome extension “ChromeiQL”. Then, set the endpoint as “/graphql”.

After that, input your GraphQL query on the left side of the “ChromeiQL” interface and click on the “Run” button. Now, you will get the result on the right side!

hope this will solve your problem, please let me know if this helps you!

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.