Created
February 28, 2021 12:15
-
-
Save sgorev/2faa7cbf86b7fe6d9b314c6dc8720b5e to your computer and use it in GitHub Desktop.
GraphQL example for webonyx/graphql-php library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'vendor/autoload.php'; | |
use GraphQL\GraphQL; | |
use GraphQL\Type\Schema; | |
use GraphQL\Type\Definition\ObjectType; | |
use GraphQL\Type\Definition\Type; | |
use GraphQL\Server\StandardServer; | |
use Laminas\Diactoros\ServerRequestFactory; | |
use GraphQL\Server\ServerConfig; | |
use GraphQL\Error\DebugFlag; | |
$flats_item = new ObjectType( | |
[ | |
'name' => 'FlatItem', | |
'fields' => [ | |
'id' => Type::int(), | |
'floor' => Type::int(), | |
'num' => Type::int(), | |
'price' => Type::int(), | |
'area_total' => Type::int(), | |
'complex' => Type::string() | |
] | |
] | |
); | |
$flats_items = new ObjectType( | |
[ | |
'name' => 'FlatsItems', | |
'fields' => [ | |
'items' => Type::listof($flats_item) | |
] | |
] | |
); | |
$flats = [ | |
'type' => $flats_items, | |
'args' => [ | |
'price_min' => Type::int(), | |
'price_max' => Type::int(), | |
], | |
'resolve' => function ($rootValue, $args) { | |
$flats = [ | |
[ | |
'id' => 1, | |
'floor' => 2, | |
'num' => 3, | |
'price' => 100, | |
'area_total' => 10, | |
'complex' => 'Complex 1' | |
], | |
[ | |
'id' => 2, | |
'floor' => 2, | |
'num' => 3, | |
'price' => 200, | |
'area_total' => 10, | |
'complex' => 'Complex 2' | |
], | |
[ | |
'id' => 3, | |
'floor' => 2, | |
'num' => 3, | |
'price' => 300, | |
'area_total' => 10, | |
'complex' => 'Complex 3' | |
], | |
[ | |
'id' => 3, | |
'floor' => 2, | |
'num' => 3, | |
'price' => 400, | |
'area_total' => 10, | |
'complex' => 'Complex 1' | |
], | |
]; | |
return ['items' => array_filter($flats,function($flat) use ($args) { | |
if($flat['price']>$args['price_min']) | |
return true; | |
else | |
return false; | |
})]; | |
} | |
]; | |
$query = new ObjectType([ | |
'name' => 'Query', | |
'fields' => [ | |
'flats' => $flats, | |
] | |
]); | |
$schema = new Schema([ | |
'query' => $query, | |
]); | |
$server_config = ServerConfig::create() | |
->setSchema($schema); | |
$request = ServerRequestFactory::fromGlobals(); | |
$rawInput = file_get_contents('php://input'); | |
$input = json_decode($rawInput, true); | |
$request = $request->withParsedBody($input); | |
$server = new StandardServer($server_config); | |
$result = $server->executePsrRequest($request); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I follow this but I have an error. The schema does not define the required query root type.