## 1、注册模块
`app/code/Test/TestGraphQl/registration.php`
~~~PHP
<?php
/**
* Webkul Software.
*
* @category Webkul
* @package Test_TestGraphQl
* @author Webkul
* @license https://store.webkul.com/license.html
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Test_TestGraphQl',
__DIR__
);
~~~
## 2、定义模块
`app/code/Test/TestGraphQl/etc/module.xml`
~~~PHP
<?xml version="1.0"?>
<!--
/**
* Webkul Software.
*
* @category Webkul
* @package Test_TestGraphQl
* @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="Test_TestGraphQl" >
<sequence>
<module name="Magento_Customer"/>
<module name="Magento_Authorization"/>
<module name="Magento_GraphQl"/>
</sequence>
</module>
</config>
~~~
## 3、定义api格式
`app/code/Test/TestGraphQl/etc/schema.graphqls`
~~~PHP
#Magento Customer GraphQl Schema
type Query {
testcustomer: Testcustomer @resolver(class: "Test\\TestGraphQl\\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
}
~~~
## 4、创建解析器
`app/code/Test/TestGraphQl/``Model``/``Resolver``/Customer.php`
~~~PHP
<?php
declare(strict_types=1);
namespace Test\TestGraphQl\Model\Resolver;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Test\TestGraphQl\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;
/**
* 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;
}
/**
* {@inheritdoc}
*/
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) : Value {
if ((!$context->getUserId()) || $context->getUserType() == UserContextInterface::USER_TYPE_GUEST) {
throw new GraphQlAuthorizationException(
__(
'Current customer does not have access to the resource "%1"',
[\Magento\Customer\Model\Customer::ENTITY]
)
);
}
try {
$data = $this->getCustomerData($context->getUserId());
$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()));
}
}
/**
*
* @param int $context
* @return array
* @throws NoSuchEntityException|LocalizedException
*/
private function getCustomerData($customerId) : array
{
try {
$customerData = [];
$customerColl = $this->customerFactory->create()->getCollection()
->addFieldToFilter("entity_id", ["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()));
}
}
}
~~~
## 5、运行命令安装模块
命令略
## 6、检查api响应
**Request:**
~~~GraphQL
{
testcustomer {
entity_id,
firstname,
lastname,
email
}
}
~~~
**Response:**
~~~GraphQL
{
"data": {
"testcustomer": {
"entity_id": 204,
"firstname": "xx",
"lastname": "xxx",
"email": "xxx@foxmail.com"
}
}
}
~~~
Tips: 该响应需要先授权再请求