forked from nuwave/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphQL.php
448 lines (395 loc) · 14.2 KB
/
GraphQL.php
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
<?php
namespace Nuwave\Lighthouse;
use GraphQL\Error\DebugFlag;
use GraphQL\Error\Error;
use GraphQL\Error\SyntaxError;
use GraphQL\Executor\ExecutionResult;
use GraphQL\GraphQL as GraphQLBase;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\Parser;
use GraphQL\Server\Helper as GraphQLHelper;
use GraphQL\Server\OperationParams;
use GraphQL\Server\RequestError;
use GraphQL\Type\Schema;
use Illuminate\Container\Container;
use Illuminate\Contracts\Cache\Factory as CacheFactory;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Collection;
use Nuwave\Lighthouse\Events\BuildExtensionsResponse;
use Nuwave\Lighthouse\Events\EndExecution;
use Nuwave\Lighthouse\Events\EndOperationOrOperations;
use Nuwave\Lighthouse\Events\ManipulateResult;
use Nuwave\Lighthouse\Events\StartExecution;
use Nuwave\Lighthouse\Events\StartOperationOrOperations;
use Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry;
use Nuwave\Lighthouse\Execution\DataLoader\BatchLoader;
use Nuwave\Lighthouse\Execution\ErrorPool;
use Nuwave\Lighthouse\Schema\SchemaBuilder;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Nuwave\Lighthouse\Support\Contracts\ProvidesValidationRules;
use Nuwave\Lighthouse\Support\Utils as LighthouseUtils;
/**
* The main entrypoint to GraphQL execution.
*
* @phpstan-import-type ErrorsHandler from \GraphQL\Executor\ExecutionResult
*/
class GraphQL
{
/**
* @var \Nuwave\Lighthouse\Schema\SchemaBuilder
*/
protected $schemaBuilder;
/**
* @var \Illuminate\Pipeline\Pipeline
*/
protected $pipeline;
/**
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $eventDispatcher;
/**
* @var \Nuwave\Lighthouse\Execution\ErrorPool
*/
protected $errorPool;
/**
* @var \Nuwave\Lighthouse\Support\Contracts\ProvidesValidationRules
*/
protected $providesValidationRules;
/**
* @var \GraphQL\Server\Helper
*/
protected $graphQLHelper;
/**
* @var \Illuminate\Contracts\Config\Repository
*/
protected $configRepository;
/**
* Lazily initialized.
*
* @var ErrorsHandler
*/
protected $errorsHandler;
public function __construct(
SchemaBuilder $schemaBuilder,
Pipeline $pipeline,
EventDispatcher $eventDispatcher,
ErrorPool $errorPool,
ProvidesValidationRules $providesValidationRules,
GraphQLHelper $graphQLHelper,
ConfigRepository $configRepository
) {
$this->schemaBuilder = $schemaBuilder;
$this->pipeline = $pipeline;
$this->eventDispatcher = $eventDispatcher;
$this->errorPool = $errorPool;
$this->providesValidationRules = $providesValidationRules;
$this->graphQLHelper = $graphQLHelper;
$this->configRepository = $configRepository;
}
/**
* Run one or more GraphQL operations against the schema.
*
* @param \GraphQL\Server\OperationParams|array<int, \GraphQL\Server\OperationParams> $operationOrOperations
*
* @return array<string, mixed>|array<int, array<string, mixed>>
*/
public function executeOperationOrOperations($operationOrOperations, GraphQLContext $context): array
{
$this->eventDispatcher->dispatch(
new StartOperationOrOperations($operationOrOperations)
);
$resultOrResults = LighthouseUtils::mapEach(
/**
* @return array<string, mixed>
*/
function (OperationParams $operationParams) use ($context): array {
return $this->executeOperation($operationParams, $context);
},
$operationOrOperations
);
$this->eventDispatcher->dispatch(
new EndOperationOrOperations($resultOrResults)
);
return $resultOrResults;
}
/**
* Run a single GraphQL operation against the schema and get a result.
*
* @return array<string, mixed>
*/
public function executeOperation(OperationParams $params, GraphQLContext $context): array
{
$errors = $this->graphQLHelper->validateOperationParams($params);
if (count($errors) > 0) {
$errors = array_map(
static function (RequestError $err): Error {
return Error::createLocatedError($err);
},
$errors
);
return $this->serializable(
new ExecutionResult(null, $errors)
);
}
$queryString = $params->query;
if (is_string($queryString)) {
$result = $this->parseAndExecuteQuery(
$queryString,
$context,
$params->variables,
null,
$params->operation
);
// @phpstan-ignore-next-line TODO remove when graphql-php 15 correctly types OperationParams::$query as nullable
} else {
try {
$result = $this->executeParsedQuery(
$this->loadPersistedQuery($params->queryId),
$context,
$params->variables,
null,
$params->operation
);
} catch (Error $error) {
return $this->serializable(
new ExecutionResult(null, [$error])
);
}
}
return $this->serializable($result);
}
/**
* Parses query and executes it.
*
* @param array<string, mixed>|null $variables
* @param mixed|null $rootValue
*/
public function parseAndExecuteQuery(
string $query,
GraphQLContext $context,
?array $variables = [],
$rootValue = null,
?string $operationName = null
): ExecutionResult {
try {
$parsedQuery = $this->parse($query);
} catch (SyntaxError $syntaxError) {
return new ExecutionResult(null, [$syntaxError]);
}
return $this->executeParsedQuery($parsedQuery, $context, $variables, $rootValue, $operationName);
}
/**
* Parse the given query string into a DocumentNode.
*
* Caches the parsed result if the query cache is enabled in the configuration.
*
* @throws SyntaxError
*/
public function parse(string $query): DocumentNode
{
$cacheConfig = $this->configRepository->get('lighthouse.query_cache');
if (! $cacheConfig['enable']) {
return Parser::parse($query);
}
$cacheFactory = Container::getInstance()->make(CacheFactory::class);
assert($cacheFactory instanceof CacheFactory);
$store = $cacheFactory->store($cacheConfig['store']);
return $store->remember(
'lighthouse:query:' . hash('sha256', $query),
$cacheConfig['ttl'],
static function () use ($query): DocumentNode {
return Parser::parse($query);
}
);
}
/**
* Execute a GraphQL query on the Lighthouse schema and return the raw result.
*
* To render the @see \GraphQL\Executor\ExecutionResult
* you will probably want to call `->toArray($debug)` on it,
* with $debug being a combination of flags in @see \GraphQL\Error\DebugFlag
*
* @param array<string, mixed>|null $variables
* @param mixed|null $rootValue
*/
public function executeParsedQuery(
DocumentNode $query,
GraphQLContext $context,
?array $variables = [],
$rootValue = null,
?string $operationName = null
): ExecutionResult {
// Building the executable schema might take a while to do,
// so we do it before we fire the StartExecution event.
// This allows tracking the time for batched queries independently.
$schema = $this->schemaBuilder->schema();
$this->eventDispatcher->dispatch(
new StartExecution($schema, $query, $variables, $operationName, $context)
);
$result = GraphQLBase::executeQuery(
$schema,
$query,
$rootValue,
$context,
$variables,
$operationName,
null,
$this->providesValidationRules->validationRules()
);
/** @var array<\Nuwave\Lighthouse\Execution\ExtensionsResponse|null> $extensionsResponses */
$extensionsResponses = (array) $this->eventDispatcher->dispatch(
new BuildExtensionsResponse()
);
foreach ($extensionsResponses as $extensionsResponse) {
if (null !== $extensionsResponse) {
$result->extensions[$extensionsResponse->key()] = $extensionsResponse->content();
}
}
foreach ($this->errorPool->errors() as $error) {
$result->errors[] = $error;
}
// Allow listeners to manipulate the result after each resolved query
$this->eventDispatcher->dispatch(
new ManipulateResult($result)
);
$this->eventDispatcher->dispatch(
new EndExecution($result)
);
$this->cleanUpAfterExecution();
return $result;
}
/**
* Convert the result to a serializable array.
*
* @return array<string, mixed>
*/
public function serializable(ExecutionResult $result): array
{
$result->setErrorsHandler($this->errorsHandler());
return $result->toArray($this->debugFlag());
}
/**
* Loads persisted query from the query cache.
*
* @throws Error if this feature is disabled or no query is found
*/
protected function loadPersistedQuery(string $sha256hash): DocumentNode
{
$lighthouseConfig = $this->configRepository->get('lighthouse');
$cacheConfig = $lighthouseConfig['query_cache'] ?? null;
if (
! ($lighthouseConfig['persisted_queries'] ?? false)
|| ! ($cacheConfig['enable'] ?? false)
) {
// https://github.com/apollographql/apollo-server/blob/37a5c862261806817a1d71852c4e1d9cdb59eab2/packages/apollo-server-errors/src/index.ts#L240-L248
throw new Error(
'PersistedQueryNotSupported',
null,
null,
[],
null,
null,
['code' => 'PERSISTED_QUERY_NOT_SUPPORTED']
);
}
$cacheFactory = Container::getInstance()->make(CacheFactory::class);
assert($cacheFactory instanceof CacheFactory);
$store = $cacheFactory->store($cacheConfig['store']);
$document = $store->get("lighthouse:query:{$sha256hash}");
if (null === $document) {
// https://github.com/apollographql/apollo-server/blob/37a5c862261806817a1d71852c4e1d9cdb59eab2/packages/apollo-server-errors/src/index.ts#L230-L239
throw new Error(
'PersistedQueryNotFound',
null,
null,
[],
null,
null,
['code' => 'PERSISTED_QUERY_NOT_FOUND']
);
}
return $document;
}
protected function cleanUpAfterExecution(): void
{
BatchLoaderRegistry::forgetInstances();
$this->errorPool->clear();
// TODO remove in v6
BatchLoader::forgetInstances();
}
/**
* @return ErrorsHandler
*/
protected function errorsHandler(): callable
{
if (! isset($this->errorsHandler)) {
// @phpstan-ignore-next-line callable is not recognized correctly and can not be type-hinted to match
return $this->errorsHandler = function (array $errors, callable $formatter): array {
// User defined error handlers, implementing \Nuwave\Lighthouse\Execution\ErrorHandler
// This allows the user to register multiple handlers and pipe the errors through.
$handlers = [];
foreach ($this->configRepository->get('lighthouse.error_handlers', []) as $handlerClass) {
$handlers[] = Container::getInstance()->make($handlerClass);
}
return (new Collection($errors))
->map(function (Error $error) use ($handlers, $formatter): ?array {
return $this->pipeline
->send($error)
->through($handlers)
->then(
fn (?Error $error): ?array => null === $error
? null
: $formatter($error)
);
})
->filter()
->all();
};
}
return $this->errorsHandler;
}
protected function debugFlag(): int
{
// If debugging is set to false globally, do not add GraphQL specific
// debugging info either. If it is true, then we fetch the debug
// level from the Lighthouse configuration.
return $this->configRepository->get('app.debug')
? (int) $this->configRepository->get('lighthouse.debug')
: DebugFlag::NONE;
}
/**
* This method will be removed in the next major update. Please use executeParsedQuery or parseAndExecuteQuery.
*
* @param string|\GraphQL\Language\AST\DocumentNode $query
* @param array<string, mixed>|null $variables
* @param mixed|null $rootValue
*
* @see executeParsedQuery
* @see parseAndExecuteQuery
* @deprecated
*/
public function executeQuery(
$query,
GraphQLContext $context,
?array $variables = [],
$rootValue = null,
?string $operationName = null
): ExecutionResult {
if (is_string($query)) {
return $this->parseAndExecuteQuery($query, $context, $variables, $rootValue, $operationName);
}
return $this->executeParsedQuery($query, $context, $variables, $rootValue, $operationName);
}
/**
* Ensure an executable GraphQL schema is present.
*
* @deprecated
* @see \Nuwave\Lighthouse\Schema\SchemaBuilder::schema()
*/
public function prepSchema(): Schema
{
return $this->schemaBuilder->schema();
}
}