GraphQL
快速开始
namespace App\Controller;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use Hyperf\Di\Annotation\Inject;
use Hyperf\GraphQL\Annotation\Query;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
/**
* @Controller()
*/
class GraphQLController
{
/**
* @Inject()
*/
protected $schema;
/**
* @PostMapping(path="/graphql")
*/
public function test(RequestInterface $request)
{
$rawInput = $request->getBody()->getContents();
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
return GraphQL::executeQuery($this->schema, $query, null, null, $variableValues)->toArray();
}
/**
* @Query()
*/
public function hello(string $name): string
{
return $name;
}
}
查询:
"hello": "graphql"
}
}
类型映射
在 GraphQLController
中加入
<?php
use App\Model\Product;
/**
* @Query()
*/
public function product(string $name, float $price): Product
{
return new Product($name, $price);
}
响应:
{
"data": {
"hello": "graphql",
"product": {
"name": "goods",
"price": 156.5
}
}