Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Last active May 23, 2017 13:20
Show Gist options
  • Save leocavalcante/9e61ca6065130e37737f24892d81fa40 to your computer and use it in GitHub Desktop.
Save leocavalcante/9e61ca6065130e37737f24892d81fa40 to your computer and use it in GitHub Desktop.
<?php
require_once __DIR__.'/vendor/autoload.php';
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Schema;
use GraphQL\GraphQL;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'echo' => [
'type' => Type::string(),
'args' => [
'message' => ['type' => Type::string()],
],
'resolve' => function ($root, $args) {
return $root['prefix'].$args['message'];
}
],
],
]);
$mutationType = new ObjectType([
'name' => 'Calc',
'fields' => [
'sum' => [
'type' => Type::int(),
'args' => [
'x' => ['type' => Type::int()],
'y' => ['type' => Type::int()],
],
'resolve' => function ($root, $args) {
return $args['x'] + $args['y'];
},
],
],
]);
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType,
]);
$rawInput = file_get_contents('php://input');
try {
$rootValue = ['prefix' => 'You said: '];
$result = GraphQL::execute($schema, $rawInput, $rootValue);
} catch (\Exception $e) {
$result = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($result);
@leocavalcante
Copy link
Author

php -S localhost:8000 graphql.php
curl http://localhost:8000 -d "query { echo(message: \"Hello\") }"
curl http://localhost:8000 -d "mutation { sum(x: 2, y: 2) }"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment