-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphqlController.php
More file actions
154 lines (132 loc) · 5.28 KB
/
GraphqlController.php
File metadata and controls
154 lines (132 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
namespace Drupal\simple_graphql\Controller;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\simple_graphql\Plugin\SchemaPluginManager;
use Drupal\simple_graphql\SchemaInterface;
use GraphQL\Error\DebugFlag;
use GraphQL\Language\Parser;
use GraphQL\Server\ServerConfig;
use GraphQL\Server\StandardServer;
use GraphQL\Utils\AST;
use GraphQL\Utils\BuildSchema;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class GraphqlController extends ControllerBase {
protected SchemaPluginManager $pluginManager;
protected CacheBackendInterface $cache;
public function __construct(SchemaPluginManager $pluginManager, CacheBackendInterface $cache) {
$this->pluginManager = $pluginManager;
$this->cache = $cache;
}
public static function create(ContainerInterface $container) {
return new static($container->get("plugin.manager.simple_graphql.schema"), $container->get("cache.default"));
}
public function graphql(string $schema, ServerRequestInterface $request) {
/** @var SchemaInterface */
$plugin = $this->pluginManager->createInstance($schema);
$definition = $this->pluginManager->getDefinition($schema);
$accept = $request->getHeaderLine("accept");
if (strpos($accept, "text/html") !== false) {
return new Response($this->graphiql($definition["path"]));
}
$serverConfig = new ServerConfig();
$serverConfig->setSchema($this->getSchema($schema, $definition, $plugin));
$serverConfig->setErrorsHandler(function (array $errors, callable $formatter) {
foreach ($errors as $error) {
watchdog_exception("simple_graphql", $error);
}
return array_map($formatter, $errors);
});
$serverConfig->setDebugFlag(DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE);
$serverConfig->setQueryBatching(true);
$serverConfig->setContext(["pluginId" => $definition["id"]]);
$decoratedServerConfig = $plugin->configureServer($serverConfig);
$server = new StandardServer($decoratedServerConfig);
// TODO persist queries.
// 'persistentQueryLoader' => function($queryId, $params) {
// $c = $this->cache->get('simple_graphql.persisted_query.' . $queryId);
// if ($c === FALSE) {
// throw new RequestError('PersistedQueryNotFound');
// }
// return $c->data;
// }
if (stripos($request->getHeaderLine("content-type"), "application/json") !== false) {
$input = Json::decode($request->getBody()->getContents());
// $this->persistQueries($input);
if (\Drupal::state()->get('simple_graphql_debug') === 'verbose') {
\Drupal::logger('simple_graphql')
->info('<pre>' . print_r($input, 1) . '</pre>');
}
$request = $request->withParsedBody($input);
}
$output = $server->executePsrRequest($request);
return new JsonResponse($output);
}
// TODO
// public function persistQueries($input) {
// if (!is_array($input)) {
// $input = [$input];
// }
// foreach ($input as $i) {
// if (!empty($i["query"]) && !empty($i["extensions"]["persistedQuery"]["sha256Hash"])) {
// $hash = hash("sha256", $i["query"]);
// $this->cache()->set("simple_graphql.persisted_query." . $hash, $i["query"]);
// }
// }
// }
public function getSchema($pluginId, $definition, $plugin) {
$key = "simple_graphql.schema." . $pluginId;
if ($c = $this->cache->get($key)) {
$doc = AST::fromArray($c->data);
} else {
$path = DRUPAL_ROOT . "/" . \Drupal::service('extension.list.module')->getPath($definition["provider"]) . "/" . $definition["schemaFile"];
$doc = Parser::parse(file_get_contents($path));
$this->cache->set($key, AST::toArray($doc));
}
return BuildSchema::build($doc, [$plugin, "schemaTypeConfigDecorator"]);
}
public function graphiql($path) {
return <<<HTML
<!DOCTYPE html>
<html>
<head>
<title>Graphiql</title>
<link href="https://unpkg.com/graphiql/graphiql.min.css" rel="stylesheet" />
</head>
<body style="margin: 0;">
<div id="graphiql" style="height: 100vh;"></div>
<script
crossorigin
src="https://unpkg.com/react/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/graphiql/graphiql.min.js"
></script>
<script>
const graphQLFetcher = graphQLParams =>
fetch('{$path}', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(graphQLParams),
})
.then(response => response.json())
.catch(() => response.text());
ReactDOM.render(
React.createElement(GraphiQL, { fetcher: graphQLFetcher }),
document.getElementById('graphiql'),
);
</script>
</body>
</html>
HTML;
}
}