|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +use Psr\Http\Message\ServerRequestInterface; |
| 5 | +use React\EventLoop\Factory; |
| 6 | +use React\Http\Response; |
| 7 | +use React\Http\Server; |
| 8 | + |
| 9 | +use GraphQL\GraphQL; |
| 10 | +use GraphQL\Type\Schema; |
| 11 | +use GraphQL\Executor\ExecutionResult; |
| 12 | +use GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter; |
| 13 | + |
| 14 | +use GraphQL\Type\Definition\ObjectType; |
| 15 | +use GraphQL\Type\Definition\Type; |
| 16 | + |
| 17 | +require __DIR__ . '/vendor/autoload.php'; |
| 18 | + |
| 19 | +$queryType = new ObjectType([ |
| 20 | + 'name' => 'Query', |
| 21 | + 'fields' => [ |
| 22 | + 'echo' => [ |
| 23 | + 'type' => Type::string(), |
| 24 | + 'args' => [ |
| 25 | + 'message' => Type::nonNull(Type::string()), |
| 26 | + ], |
| 27 | + 'resolve' => function($root, $args) { |
| 28 | + return $root['prefix'] . $args['message']; |
| 29 | + } |
| 30 | + ]/*, |
| 31 | + 'echo' => [ |
| 32 | + 'type' => Type::string(), |
| 33 | + 'args' => [ |
| 34 | + 'message' => Type::nonNull(Type::string()), |
| 35 | + ], |
| 36 | + 'resolve' => function ($root, $args) { |
| 37 | + return $root['prefix'] . $args['message']; |
| 38 | + } |
| 39 | + ], |
| 40 | + */ |
| 41 | + ], |
| 42 | +]); |
| 43 | + |
| 44 | +$schema = new Schema([ |
| 45 | + 'query' => $queryType |
| 46 | +]); |
| 47 | + |
| 48 | +$loop = Factory::create(); |
| 49 | +$react = new ReactPromiseAdapter(); |
| 50 | + |
| 51 | +$server = new Server(function (ServerRequestInterface $request) use ($schema, $react) { |
| 52 | + $rawInput = (string)$request->getBody(); |
| 53 | + $input = json_decode($rawInput, true); |
| 54 | + $query = $input['query']; |
| 55 | + $variableValues = isset($input['variables']) ? $input['variables'] : null; |
| 56 | + $rootValue = ['prefix' => 'You said: ']; |
| 57 | + $promise = GraphQL::promiseToExecute($react, $schema, $query, $rootValue, null, $variableValues); |
| 58 | + return $promise->then(function(ExecutionResult $result) { |
| 59 | + $output = $result->toArray(); |
| 60 | + return new Response( |
| 61 | + 200, |
| 62 | + array( |
| 63 | + 'Content-Type' => 'application/json' |
| 64 | + ), |
| 65 | + json_encode($output) |
| 66 | + ); |
| 67 | + }); |
| 68 | +}); |
| 69 | +$socket = new \React\Socket\Server('0.0.0.0:3000', $loop); |
| 70 | +$server->listen($socket); |
| 71 | +echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; |
| 72 | +$loop->run(); |
0 commit comments