GraphQL
本文檔假定你熟悉GraphQL的概念。如果不是這樣,請首先在官方網(wǎng)站上面了解 GraphQL。
依賴類庫
composer require webonyx/graphql-php
EasySwoole Http 中使用
其實在EasySwoole Http服務器中使用,本質(zhì)問題在于,如何得到RAW_POST過來的json數(shù)據(jù)。我們直接貼代碼:
namespace App\HttpController;
use EasySwoole\Http\AbstractInterface\Controller;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
class Index extends Controller
{
function index()
{
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'echo' => [
'type' => Type::string(),
'args' => [
'message' => Type::nonNull(Type::string()),
],
'resolve' => function ($root, $args) {
return $root['prefix'] . $args['message'];
}
],
],
]);
$schema = new Schema([
'query' => $queryType
]);
$input = $this->json();
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = ['prefix' => 'You said: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
$this->writeJson(200,$output);
}
}