GraphQL

    快速开始

    1. namespace App\Controller;
    2. use GraphQL\GraphQL;
    3. use GraphQL\Type\Schema;
    4. use Hyperf\Di\Annotation\Inject;
    5. use Hyperf\GraphQL\Annotation\Query;
    6. use Hyperf\HttpServer\Annotation\Controller;
    7. use Hyperf\HttpServer\Annotation\PostMapping;
    8. use Hyperf\HttpServer\Contract\RequestInterface;
    9. /**
    10. * @Controller()
    11. */
    12. class GraphQLController
    13. {
    14. /**
    15. * @Inject()
    16. */
    17. protected $schema;
    18. /**
    19. * @PostMapping(path="/graphql")
    20. */
    21. public function test(RequestInterface $request)
    22. {
    23. $rawInput = $request->getBody()->getContents();
    24. $input = json_decode($rawInput, true);
    25. $query = $input['query'];
    26. $variableValues = isset($input['variables']) ? $input['variables'] : null;
    27. return GraphQL::executeQuery($this->schema, $query, null, null, $variableValues)->toArray();
    28. }
    29. /**
    30. * @Query()
    31. */
    32. public function hello(string $name): string
    33. {
    34. return $name;
    35. }
    36. }

    查询:

    1. "hello": "graphql"
    2. }
    3. }

    类型映射

    GraphQLController 中加入

    1. <?php
    2. use App\Model\Product;
    3. /**
    4. * @Query()
    5. */
    6. public function product(string $name, float $price): Product
    7. {
    8. return new Product($name, $price);
    9. }

    响应:

    1. {
    2. "data": {
    3. "hello": "graphql",
    4. "product": {
    5. "name": "goods",
    6. "price": 156.5
    7. }
    8. }