Merge pull request #142 from symm/shorthand-docs

Add example for building schema from IDL
This commit is contained in:
Vladimir Razuvaev 2017-07-11 21:49:49 +07:00 committed by GitHub
commit 5e6acb60a6
4 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,19 @@
# Parsing GraphQL IDL shorthand
Same as the Hello world example but shows how to build GraphQL schema from shorthand
and wire up some resolvers
### Run locally
```
php -S localhost:8080 ./graphql.php
```
### Try query
```
curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
```
### Try mutation
```
curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
```

View File

@ -0,0 +1,31 @@
<?php
// Test this using following command
// php -S localhost:8080 ./graphql.php &
// curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
// curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
require_once __DIR__ . '/../../vendor/autoload.php';
use GraphQL\GraphQL;
use GraphQL\Utils\BuildSchema;
try {
$schema = BuildSchema::build(file_get_contents(__DIR__ . '/schema.graphqls'));
$rootValue = include __DIR__ . '/rootvalue.php';
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
$result = GraphQL::execute($schema, $query, $rootValue, null, $variableValues);
} catch (\Exception $e) {
$result = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($result);

View File

@ -0,0 +1,35 @@
<?php
interface Resolver {
public function resolve($root, $args, $context);
}
class Addition implements Resolver
{
public function resolve($root, $args, $context)
{
return $args['x'] + $args['y'];
}
}
class Echoer implements Resolver
{
public function resolve($root, $args, $context)
{
return $root['prefix'].$args['message'];
}
}
return [
'sum' => function($root, $args, $context) {
$sum = new Addition();
return $sum->resolve($root, $args, $context);
},
'echo' => function($root, $args, $context) {
$echo = new Echoer();
return $echo->resolve($root, $args, $context);
},
'prefix' => 'You said: ',
];

View File

@ -0,0 +1,13 @@
schema {
query: Query
mutation: Calc
}
type Calc {
sum(x: Int, y: Int): Int
}
type Query {
echo(message: String): String
}