php graph函数,开始使用graphql-php:如何从.graphql文件中将解析器函数添加到模式中?...

我是GraphQL的新手,想要使用graphql-php进行编程,以便构建一个简单的API来开始 . 我正在阅读文档并试用这些例子,但我在开始时就陷入了困境 .

我希望我的架构存储在 schema.graphql 文件中,而不是手动构建它,所以我按照文档说明了如何做到这一点,它确实有效:

// graph-ql is installed via composer

require('../vendor/autoload.php');

use GraphQL\Language\Parser;

use GraphQL\Utils\BuildSchema;

use GraphQL\Utils\AST;

use GraphQL\GraphQL;

try {

$cacheFilename = 'cached_schema.php';

// caching, as recommended in the docs, is disabled for testing

// if (!file_exists($cacheFilename)) {

$document = Parser::parse(file_get_contents('./schema.graphql'));

file_put_contents($cacheFilename, "<?php \nreturn " . var_export(AST::toArray($document), true) . ';');

/*} else {

$document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well

}*/

$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {

// In the docs, this function is just empty, but I needed to return the $typeConfig, otherwise I got an error

return $typeConfig;

};

$schema = BuildSchema::build($document, $typeConfigDecorator);

$context = (object)array();

// this has been taken from one of the examples provided in the repo

$rawInput = file_get_contents('php://input');

$input = json_decode($rawInput, true);

$query = $input['query'];

$variableValues = isset($input['variables']) ? $input['variables'] : null;

$rootValue = ['prefix' => 'You said: '];

$result = GraphQL::executeQuery($schema, $query, $rootValue, $context, $variableValues);

$output = $result->toArray();

} catch (\Exception $e) {

$output = [

'error' => [

'message' => $e->getMessage()

]

];

}

header('Content-Type: application/json; charset=UTF-8');

echo json_encode($output);

这就是我的 schema.graphql 文件的样子:

schema {

query: Query

}

type Query {

products: [Product!]!

}

type Product {

id: ID!,

type: ProductType

}

enum ProductType {

HDRI,

SEMISPHERICAL_HDRI,

SOUND

}

我可以用例如查询它

query {

__schema {types{name}}

}

这将按预期返回元数据 . 但是,当然现在我想查询实际的产品数据并从数据库中获取,为此我需要定义一个解析器函数 .

http://webonyx.github.io/graphql-php/type-system/type-language/状态的文档:"By default, such schema is created without any resolvers. We have to rely on default field resolver and root value in order to execute a query against this schema." - 但没有这样做的例子 .

如何为每个类型/字段添加解析器功能?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值