Graphql访问magento2(前端使用)

Graphql和RestApi一样,是访问接口的一种方式,具体在magento2中的不同之处主要是:

        1)Graphql可以一次性访问多个接口,一般提供给magento2前端使用;

        2)RestApi一次只能访问一个接口,一般提供给第三方调用。

具体异同参考:GraphQL vs REST APIs 完整指南-CSDN博客

(1)magento2中要新增Graphql接口需要执行以下几个步骤:

        a)首先要在etc/目录下新建一个schema.graphqls文件,在文件中声明新增的是query还是mutation类型。这里以query举例,声明了一个Graphql接口getProduct2VendorInfo,入参为itemId,int类型,返回值为TodoList类型,TodoList定义在下方,Item是ToDoList类型中的嵌套类型,同样在文件中声明。

官方文档:Extend an existing GraphQL schema

type Query {
    getProduct2VendorInfo(itemId: Int): TodoList
      @resolver(class: "Bcn\\ToDoCrud\\Model\\Resolver\\GetToDoListResolver")
      @doc(description: "get todoList item detail.")
}

type TodoList {
    items: [Item] @doc(description: "To do list.")
    code: String @doc(description: "Response status code.")
}

type Item {
    itemId: Int
    content: String @doc(description: "Detail of the item.")
}

        b) 在Model/下新建目录Resolver,之后在Resolver目录下新建Graphql接口处理类GetToDoListResolver(:接口处理类一定要实现Magento\Framework\GraphQl\Query\下的ResolverInterface接口),逻辑同RestApi,只不过访问方式不同。

官方文档:GraphQL resolvers

<?php


namespace Bcn\ToDoCrud\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 Bcn\ToDoCrud\Model\ResourceModel\ToDoList\CollectionFactory;
use phpDocumentor\Reflection\Types\Collection;

class GetToDoListResolver implements ResolverInterface
{
    public $collectionFactory;

    public function __construct(CollectionFactory $collectionFactory)
    {
        $this->collectionFactory = $collectionFactory;
    }

    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        $itemId = $args['itemId'];
//        $itemId = 2;
        $a = $this->collectionFactory->create();
        $a->selectById($itemId);
        $a->load();
        $items = [];
        foreach ($a->getItems() as $item) {
            array_push($items,[
                    'itemId'=>$item->getItemId(),
                    'content'=>$item->getContent()
                ]);
        }
        $todoListData = ["items" => $items, "code"=>"200"];
        return $todoListData;
    }
}

c)执行命令php bin/magento setup:di:compile,在postman访问

其中参数XDEBUG_SESSION_START=13463为编译模式。        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值