x-graphql/http-schema

基于HTTP构建GraphQL模式(又称远程模式)

0.9.0 2024-04-10 10:16 UTC

This package is auto-updated.

Last update: 2024-09-10 11:17:55 UTC


README

unit tests codecov

帮助构建和执行GraphQL模式(即远程模式)。

入门指南

通过Composer安装此包

composer require x-graphql/http-schema

此库需要PSR-18客户端Httplug Async客户端来发送异步请求。如果您还没有安装,请运行以下命令。

composer require php-http/guzzle7-adapter

用法

此库为您提供两种构建模式策略

  • 从模式定义语言(SDL)构建,此策略用于限制用户可以访问的字段。
  • 从内省查询构建,使用此策略将对内省模式进行HTTP请求,用户可以访问所有字段。

从SDL

use GraphQL\GraphQL;
use XGraphQL\HttpSchema\HttpDelegator;
use XGraphQL\HttpSchema\HttpSchemaFactory;

$delegator = new HttpDelegator('https://countries.trevorblades.com/');
$schema = HttpSchemaFactory::createFromSDL(
$delegator,
<<<'SDL'
type Query {
  countries: [Country!]!
}

type Country {
  name: String!
}
SDL
);

$result = GraphQL::executeQuery($schema, 'query { countries { name } }');

var_dump($result->toArray());

从内省查询

use GraphQL\GraphQL;
use XGraphQL\HttpSchema\HttpDelegator;
use XGraphQL\HttpSchema\HttpSchemaFactory;

$delegator = new HttpDelegator('https://countries.trevorblades.com/');
$schema = HttpSchemaFactory::createFromIntrospectionQuery($delegator);
$result = GraphQL::executeQuery($schema, 'query { countries { name } }');

var_dump($result->toArray());

缓存模式

为了优化从SDL或内省查询构建模式的时间,您可以将PSR-16实例放入工厂方法中以缓存构建后的模式

use XGraphQL\HttpSchema\HttpDelegator;
use XGraphQL\HttpSchema\HttpSchemaFactory;

/// $psr16Cache = ....
$delegator = new HttpDelegator('https://countries.trevorblades.com/');
$schemaFromSDL = HttpSchemaFactory::createFromSDL($delegator, /// $sdl, $psr16Cache);
$schemaFromIntrospection = HttpSchemaFactory::createFromIntrospectionQuery($delegator, /// $psr16Cache);

/// ........

致谢

Minh Vuong创建