Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Created January 18, 2021 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwaidelich/3e686a3506b6869a4fbf6b85df61b841 to your computer and use it in GitHub Desktop.
Save bwaidelich/3e686a3506b6869a4fbf6b85df61b841 to your computer and use it in GitHub Desktop.
Minimal GraphQL example for Flow for interface types
<?php
declare(strict_types=1);
namespace Some\App;
use GraphQL\Error\DebugFlag;
use GraphQL\GraphQL;
use GraphQL\Utils\BuildSchema;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class GraphQlMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// TODO handle exceptions
$input = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
$typeConfigDecorator = static function(array $typeConfig, $typeDefinitionNode) {
$typeConfig['resolveType'] = static fn($a) => 'CustomerAccount';
return $typeConfig;
};
// TODO cache this (see https://webonyx.github.io/graphql-php/type-system/type-language/#performance-considerations)
$schema = BuildSchema::build(file_get_contents('resource://Some.App/Private/schema.graphql'), $typeConfigDecorator);
$rootValue = [
'node' => fn($rootValue, array $args, $context) => [
'id' => $args['id'],
'customerName' => 'John Doe',
],
];
// TODO handle exceptions
$result = GraphQL::executeQuery($schema, $input['query'], $rootValue, null, $input['variables'] ?? null)
// TODO remove debug flag
->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE);
// TODO handle exceptions
$responseBody = \json_encode($result, JSON_THROW_ON_ERROR);
return new Response(200, ['Content-Type' => 'application/json'], $responseBody);
}
}
interface Node {
id: ID!
}
type CustomerAccount implements Node {
id: ID!
customerName: String!
}
type Query {
node(
id: ID!
): Node
}
Neos:
Flow:
http:
middlewares:
'graphql':
position: 'start'
middleware: 'Some\App\GraphQlMiddleware'
@bwaidelich
Copy link
Author

The corresponding query could look like this:

{
  node(id: "foo") {
    id
    ... on CustomerAccount {
      customerName
    }
  }
}

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