Skip to content
Navigation Menu
{{ message }}
forked from nuwave/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakesGraphQLRequestsLumen.php
More file actions
279 lines (242 loc) · 9.17 KB
/
Copy pathMakesGraphQLRequestsLumen.php
File metadata and controls
279 lines (242 loc) · 9.17 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
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
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\Testing;
use GraphQL\Type\Introspection;
use Illuminate\Container\Container;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Support\Arr;
use Illuminate\Testing\TestResponse;
use Nuwave\Lighthouse\Http\Responses\MemoryStream;
use Nuwave\Lighthouse\Subscriptions\BroadcastDriverManager;
use Nuwave\Lighthouse\Subscriptions\Broadcasters\LogBroadcaster;
use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster;
use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse;
use PHPUnit\Framework\Assert;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Testing helpers for making requests to the GraphQL endpoint.
*
* @mixin \Laravel\Lumen\Testing\Concerns\MakesHttpRequests
*
* @deprecated lumen support will be removed in the next major version
*/
trait MakesGraphQLRequestsLumen // @phpstan-ignore trait.unused (hard to set up testing for)
{
/**
* Stores the result of the introspection query.
*
* On the first call to introspect() this property is set to
* cache the result, as introspection is quite expensive.
*/
protected TestResponse $introspectionResult;
/** Used to test deferred queries. */
protected MemoryStream $deferStream;
/**
* Execute a GraphQL operation as if it was sent as a request to the server.
*
* @param string $query The GraphQL operation to send
* @param array<string, mixed> $variables The variables to include in the query
* @param array<string, mixed> $extraParams Extra parameters to add to the JSON payload
* @param array<string, mixed> $headers HTTP headers to pass to the POST request
* @param array<string, string> $routeParams Parameters to pass to the route
*/
protected function graphQL(
string $query,
array $variables = [],
array $extraParams = [],
array $headers = [],
array $routeParams = [],
): self {
$params = ['query' => $query];
if ($variables !== []) {
$params += ['variables' => $variables];
}
$params += $extraParams;
$this->postGraphQL($params, $headers, $routeParams);
return $this;
}
/**
* Send a POST request to the GraphQL endpoint.
*
* Use this over graphQL() when you need more control or want to
* test how your server behaves on incorrect inputs.
*
* @param array<mixed, mixed> $data JSON-serializable payload
* @param array<string, string> $headers HTTP headers to pass to the POST request
* @param array<string, string> $routeParams Parameters to pass to the route
*/
protected function postGraphQL(array $data, array $headers = [], array $routeParams = []): self
{
$this->post(
$this->graphQLEndpointUrl($routeParams),
$data,
$headers,
);
return $this;
}
/**
* Send a multipart form request to the GraphQL endpoint.
*
* This is used for file uploads conforming to the specification:
* https://github.com/jaydenseric/graphql-multipart-request-spec
*
* @param array<string, mixed>|array<int, array<string, mixed>> $operations
* @param array<array<int, string>> $map
* @param array<\Illuminate\Http\UploadedFile>|array<array<mixed>> $files
* @param array<string, string> $headers Will be merged with Content-Type: multipart/form-data
* @param array<string, string> $routeParams Parameters to pass to the route
*
* @return $this
*/
protected function multipartGraphQL(
array $operations,
array $map,
array $files,
array $headers = [],
array $routeParams = [],
): self {
$parameters = [
'operations' => \Safe\json_encode($operations),
'map' => \Safe\json_encode($map),
];
$this->call(
'POST',
$this->graphQLEndpointUrl($routeParams),
$parameters,
[],
$files,
$this->transformHeadersToServerVars(array_merge(
[
'Content-Type' => 'multipart/form-data',
],
$headers,
)),
);
return $this;
}
/**
* Send the introspection query to the GraphQL server.
*
* Returns the cached first result on repeated calls.
*/
protected function introspect(): self
{
if (! isset($this->introspectionResult)) {
$this->graphQL(Introspection::getIntrospectionQuery());
$this->introspectionResult = $this->response;
}
return $this;
}
/**
* Run introspection and return a type by name, if present.
*
* @return array<string, mixed>|null
*/
protected function introspectType(string $name): ?array
{
return $this->introspectByName('data.__schema.types', $name);
}
/**
* Run introspection and return a directive by name, if present.
*
* @return array<string, mixed>|null
*/
protected function introspectDirective(string $name): ?array
{
return $this->introspectByName('data.__schema.directives', $name);
}
/**
* Run introspection and return a result from the given path by name, if present.
*
* @return array<string, mixed>|null
*/
protected function introspectByName(string $path, string $name): ?array
{
$this->introspect();
$content = $this->introspectionResult->getContent();
assert(is_string($content));
$results = data_get(
\Safe\json_decode($content, true),
$path,
);
return Arr::first(
$results,
static fn (array $result): bool => $result['name'] === $name,
);
}
/**
* Return the full URL to the GraphQL endpoint.
*
* @param array<string, string> $routeParams Parameters to pass to the route
*/
protected function graphQLEndpointUrl(array $routeParams = []): string
{
$config = Container::getInstance()->make(ConfigRepository::class);
$routeName = $config->get('lighthouse.route.name');
return route($routeName, $routeParams);
}
/**
* Send the query and capture all chunks of the streamed response.
*
* @param string $query The GraphQL query to send
* @param array<string, mixed> $variables The variables to include in the query
* @param array<string, mixed> $extraParams Extra parameters to add to the HTTP payload
* @param array<string, mixed> $headers HTTP headers to pass to the POST request
*
* @return array<int, mixed> The chunked results
*/
protected function streamGraphQL(
string $query,
array $variables = [],
array $extraParams = [],
array $headers = [],
): array {
if (! isset($this->deferStream)) {
$this->setUpDeferStream();
}
$response = $this->graphQL($query, $variables, $extraParams, $headers);
// @phpstan-ignore-next-line can be true
if (! $response->response instanceof StreamedResponse) {
Assert::fail('Expected the response to be a streamed response but got a regular response.');
}
// @phpstan-ignore-next-line not always unreachable
$response->response->send();
return $this->deferStream->chunks;
}
/** Set up the stream to make queries with `@defer`. */
protected function setUpDeferStream(): void
{
$this->deferStream = new MemoryStream();
Container::getInstance()->singleton(
CanStreamResponse::class,
fn (): MemoryStream => $this->deferStream,
);
}
/** Configure an error handler that rethrows all errors passed to it. */
protected function rethrowGraphQLErrors(): void
{
$config = Container::getInstance()->make(ConfigRepository::class);
$config->set('lighthouse.error_handlers', [RethrowingErrorHandler::class]);
}
/**
* @deprecated use TestsSubscriptions
* TODO remove in the next major version
*/
protected function setUpSubscriptionEnvironment(): void
{
$app = Container::getInstance();
$config = $app->make(ConfigRepository::class);
$config->set('lighthouse.subscriptions.queue_broadcasts', false);
$config->set('lighthouse.subscriptions.storage', 'array');
$config->set('lighthouse.subscriptions.storage_ttl', null);
// binding an instance to the container, so it can be spied on
$app->bind(Broadcaster::class, static fn (ConfigRepository $config): LogBroadcaster => new LogBroadcaster(
$config->get('lighthouse.subscriptions.broadcasters.log'),
));
$broadcastDriverManager = $app->make(BroadcastDriverManager::class);
assert($broadcastDriverManager instanceof BroadcastDriverManager);
// adding a custom driver which is a spied version of log driver
$broadcastDriverManager->extend('mock', fn () => $this->spy(LogBroadcaster::class)->makePartial());
// set the custom driver as the default driver
$config->set('lighthouse.subscriptions.broadcaster', 'mock');
}
}
You can’t perform that action at this time.
