GraphQL

本文档假定你熟悉GraphQL的概念。如果不是这样,请首先在官方网站上面了解 GraphQL。

依赖类库

  1. composer require webonyx/graphql-php

EasySwoole Http 中使用

其实在EasySwoole Http服务器中使用,本质问题在于,如何得到RAW_POST过来的json数据。我们直接贴代码:

  1. namespace App\HttpController;
  2. use EasySwoole\Http\AbstractInterface\Controller;
  3. use GraphQL\Type\Definition\ObjectType;
  4. use GraphQL\Type\Definition\Type;
  5. use GraphQL\GraphQL;
  6. use GraphQL\Type\Schema;
  7. class Index extends Controller
  8. {
  9. function index()
  10. {
  11. $queryType = new ObjectType([
  12. 'name' => 'Query',
  13. 'fields' => [
  14. 'echo' => [
  15. 'type' => Type::string(),
  16. 'args' => [
  17. 'message' => Type::nonNull(Type::string()),
  18. ],
  19. 'resolve' => function ($root, $args) {
  20. return $root['prefix'] . $args['message'];
  21. }
  22. ],
  23. ],
  24. ]);
  25. $schema = new Schema([
  26. 'query' => $queryType
  27. ]);
  28. $input = $this->json();
  29. $query = $input['query'];
  30. $variableValues = isset($input['variables']) ? $input['variables'] : null;
  31. try {
  32. $rootValue = ['prefix' => 'You said: '];
  33. $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
  34. $output = $result->toArray();
  35. } catch (\Exception $e) {
  36. $output = [
  37. 'errors' => [
  38. [
  39. 'message' => $e->getMessage()
  40. ]
  41. ]
  42. ];
  43. }
  44. $this->writeJson(200,$output);
  45. }
  46. }