amin3mej/yii2-graphql-data-provider

一个可用于连接到GraphQL服务器的数据提供器。

v0.1.0 2019-07-05 22:23 UTC

This package is auto-updated.

Last update: 2024-09-16 08:08:52 UTC


README

Yii2 GraphQL 数据提供器扩展


GraphQL的辅助工具,包括QueryHelper和ActiveDataProvider用于Yii2。

Latest Stable Version Total Downloads License

安装

安装此扩展的首选方式是通过composer

运行以下命令之一:

php composer.phar require --prefer-dist amin3mej/yii2-graphql-data-provider "*"

或者添加以下内容到你的composer.json文件的require部分:

"amin3mej/yii2-graphql-data-provider": "*"

to the require section of your composer.json.

配置

组件设置

要访问Query组件,您需要在应用程序配置中配置components数组

'components' => [
    'graphql' => [
        'class' => 'amin3mej\graphql\GraphqlQuery',
        'defaultTarget' => [
            'github' => 'https://api.github.com/graphql',
            'graphqlhub' => 'https://www.graphqlhub.com/graphql',
        ],
        'customHeaders' => [
            'Content-Type' => 'application/graphql',
            'github' => [
                'Authorization' => 'Bearer ' . $params['github.graphqlToken'],
            ],
        ],
    ],
],

您可以在此处定义目标,以便快速从您的代码中访问它们。

您还可以在此处定义一些要添加到请求中的头部。如果直接在数组中找到键,则该键被视为常用头部,并将与所有请求一起发送。如果您使用与目标相同的名称定义数组,则这些头部将仅用于该目标。

默认情况下有两个头部:

[
    'Accept' => 'application/json',
    'Content-Type' => 'application/json'
]

但您可以通过提供具有相同数组键的新头部来覆盖它们。

用法

查询

const QUERY_CHECK = <<<QUERY
query test (\$userId: Int!){
  userInfo (userId: \$userId) {
    firstname
    lastname
    email
  }
}
QUERY;

$result = Yii::$app->graphql->execute(QUERY_CHECK, ['userId' => (int) $userId], 'github');

ActiveDataProvider

use amin3mej\graphql\GraphqlDataProvider;

// If you want to use pagination in ActiveDataProvider, Set $offset and $limit in your query. Everything will be handled automatically.
const QUERY = <<<QUERY
query(\$limit: Int, \$offset: Int){
  categories (first: \$limit, skip: \$offset){
    id
    name
    icon
  }
}
QUERY;

$dataProvider = new GraphqlDataProvider([
    'query' => QUERY,
    'queryCallback' => 'data.categories', // How to access the array in responded query result? More: https://yiiframework.cn/doc/guide/2.0/en/helper-array#getting-values
    'totalCountQuery' => 'query { categoriesConnection { aggregate { count } } }',
    'target' => 'prisma',
]);

return $this->render('index', [
    'dataProvider' => $dataProvider,
]);