-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathpersisted-queries.test.ts
753 lines (701 loc) · 23.8 KB
/
persisted-queries.test.ts
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
import gql from "graphql-tag";
import { print } from "graphql";
import { times } from "lodash";
import fetchMock from "fetch-mock";
import crypto from "crypto";
import { ApolloLink, execute } from "../../core";
import { Observable } from "../../../utilities";
import { createHttpLink } from "../../http/createHttpLink";
import { createPersistedQueryLink as createPersistedQuery, VERSION } from "..";
import { itAsync } from "../../../testing";
import { toPromise } from "../../utils";
// Necessary configuration in order to mock multiple requests
// to a single (/graphql) endpoint
// see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration
fetchMock.config.overwriteRoutes = false;
afterAll(() => {
fetchMock.config.overwriteRoutes = true;
});
const makeAliasFields = (fieldName: string, numAliases: number) =>
times(numAliases, (idx) => `${fieldName}${idx}: ${fieldName}`).reduce(
(aliasBody, currentAlias) => `${aliasBody}\n ${currentAlias}`
);
const query = gql`
query Test($id: ID!) {
foo(id: $id) {
bar
${makeAliasFields("title", 1000)}
}
}
`;
const variables = { id: 1 };
const queryString = print(query);
const data = {
foo: { bar: true },
};
const response = JSON.stringify({ data });
const errors = [{ message: "PersistedQueryNotFound" }];
const errorsWithCode = [
{
message: "SomeOtherMessage",
extensions: {
code: "PERSISTED_QUERY_NOT_FOUND",
},
},
];
const giveUpErrors = [{ message: "PersistedQueryNotSupported" }];
const giveUpErrorsWithCode = [
{
message: "SomeOtherMessage",
extensions: {
code: "PERSISTED_QUERY_NOT_SUPPORTED",
},
},
];
const multipleErrors = [...errors, { message: "not logged in" }];
const errorResponse = JSON.stringify({ errors });
const errorResponseWithCode = JSON.stringify({ errors: errorsWithCode });
const giveUpResponse = JSON.stringify({ errors: giveUpErrors });
const giveUpResponseWithCode = JSON.stringify({ errors: giveUpErrorsWithCode });
const multiResponse = JSON.stringify({ errors: multipleErrors });
function sha256(data: string) {
const hash = crypto.createHash("sha256");
hash.update(data);
return hash.digest("hex");
}
const hash = sha256(queryString);
describe("happy path", () => {
beforeEach(async () => {
fetchMock.restore();
});
itAsync(
"sends a sha256 hash of the query under extensions",
(resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [uri, request] = fetchMock.lastCall()!;
expect(uri).toEqual("/graphql");
expect(request!.body!).toBe(
JSON.stringify({
operationName: "Test",
variables,
extensions: {
persistedQuery: {
version: VERSION,
sha256Hash: hash,
},
},
})
);
resolve();
}, reject);
}
);
itAsync("sends a version along with the request", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [uri, request] = fetchMock.lastCall()!;
expect(uri).toEqual("/graphql");
const parsed = JSON.parse(request!.body!.toString());
expect(parsed.extensions.persistedQuery.version).toBe(VERSION);
resolve();
}, reject);
});
itAsync("memoizes between requests", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const hashSpy = jest.fn(sha256);
const link = createPersistedQuery({ sha256: hashSpy }).concat(
createHttpLink()
);
execute(link, { query, variables }).subscribe((result) => {
expect(hashSpy).toHaveBeenCalledTimes(1);
expect(result.data).toEqual(data);
execute(link, { query, variables }).subscribe((result2) => {
expect(hashSpy).toHaveBeenCalledTimes(1);
expect(result2.data).toEqual(data);
resolve();
}, reject);
}, reject);
});
it("clears the cache when calling `resetHashCache`", async () => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const hashRefs: WeakRef<String>[] = [];
function hash(query: string) {
const newHash = new String(query);
hashRefs.push(new WeakRef(newHash));
return newHash as string;
}
const persistedLink = createPersistedQuery({ sha256: hash });
await new Promise<void>((complete) =>
execute(persistedLink.concat(createHttpLink()), {
query,
variables,
}).subscribe({ complete })
);
await expect(hashRefs[0]).not.toBeGarbageCollected();
persistedLink.resetHashCache();
await expect(hashRefs[0]).toBeGarbageCollected();
});
itAsync("supports loading the hash from other method", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const generateHash = (query: any) => Promise.resolve("foo");
const link = createPersistedQuery({ generateHash }).concat(
createHttpLink()
);
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [uri, request] = fetchMock.lastCall()!;
expect(uri).toEqual("/graphql");
const parsed = JSON.parse(request!.body!.toString());
expect(parsed.extensions.persistedQuery.sha256Hash).toBe("foo");
resolve();
}, reject);
});
itAsync("errors if unable to convert to sha256", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query: "1234", variables } as any).subscribe(
reject as any,
(error) => {
expect(error.message).toMatch(/Invalid AST Node/);
resolve();
}
);
});
itAsync("unsubscribes correctly", (resolve, reject) => {
const delay = new ApolloLink(() => {
return new Observable((ob) => {
setTimeout(() => {
ob.next({ data });
ob.complete();
}, 100);
});
});
const link = createPersistedQuery({ sha256 }).concat(delay);
const sub = execute(link, { query, variables }).subscribe(
reject,
reject,
reject
);
setTimeout(() => {
sub.unsubscribe();
resolve();
}, 10);
});
itAsync(
"should error if `sha256` and `generateHash` options are both missing",
(resolve, reject) => {
const createPersistedQueryFn = createPersistedQuery as any;
try {
createPersistedQueryFn();
reject("should have thrown an error");
} catch (error) {
expect(
(error as Error).message.indexOf(
'Missing/invalid "sha256" or "generateHash" function'
)
).toBe(0);
resolve();
}
}
);
itAsync(
"should error if `sha256` or `generateHash` options are not functions",
(resolve, reject) => {
const createPersistedQueryFn = createPersistedQuery as any;
[{ sha256: "ooops" }, { generateHash: "ooops" }].forEach((options) => {
try {
createPersistedQueryFn(options);
reject("should have thrown an error");
} catch (error) {
expect(
(error as Error).message.indexOf(
'Missing/invalid "sha256" or "generateHash" function'
)
).toBe(0);
resolve();
}
});
}
);
itAsync(
"should work with a synchronous SHA-256 function",
(resolve, reject) => {
const crypto = require("crypto");
const sha256Hash = crypto.createHmac("sha256", queryString).digest("hex");
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const link = createPersistedQuery({
sha256(data) {
return crypto.createHmac("sha256", data).digest("hex");
},
}).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [uri, request] = fetchMock.lastCall()!;
expect(uri).toEqual("/graphql");
expect(request!.body!).toBe(
JSON.stringify({
operationName: "Test",
variables,
extensions: {
persistedQuery: {
version: VERSION,
sha256Hash: sha256Hash,
},
},
})
);
resolve();
}, reject);
}
);
});
describe("failure path", () => {
beforeEach(async () => {
fetchMock.restore();
});
it.each([
["error message", errorResponse],
["error code", errorResponseWithCode],
] as const)(
"correctly identifies the error shape from the server (%s)",
(_description, failingResponse) =>
new Promise<void>((resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: failingResponse })),
{ repeat: 1 }
);
// `repeat: 1` simulates a `mockResponseOnce` API with fetch-mock:
// it limits the number of times the route can be used,
// after which the call to `fetch()` will fall through to be
// handled by any other routes defined...
// With `overwriteRoutes = false`, this means
// subsequent /graphql mocks will be used
// see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure], [, success]] = fetchMock.calls();
expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
resolve();
}, reject);
})
);
itAsync(
"sends GET for the first response only with useGETForHashedQueries",
(resolve, reject) => {
const params = new URLSearchParams({
operationName: "Test",
variables: JSON.stringify({
id: 1,
}),
extensions: JSON.stringify({
persistedQuery: {
version: 1,
sha256Hash: hash,
},
}),
}).toString();
fetchMock.get(
`/graphql?${params}`,
() => new Promise((resolve) => resolve({ body: errorResponse }))
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response }))
);
const link = createPersistedQuery({
sha256,
useGETForHashedQueries: true,
}).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure]] = fetchMock.calls();
expect(failure!.method).toBe("GET");
expect(failure!.body).not.toBeDefined();
const [, [, success]] = fetchMock.calls();
expect(success!.method).toBe("POST");
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
resolve();
}, reject);
}
);
itAsync(
"sends POST for both requests without useGETForHashedQueries",
(resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: errorResponse })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure]] = fetchMock.calls();
expect(failure!.method).toBe("POST");
expect(JSON.parse(failure!.body!.toString())).toEqual({
operationName: "Test",
variables,
extensions: {
persistedQuery: {
version: VERSION,
sha256Hash: hash,
},
},
});
const [, [, success]] = fetchMock.calls();
expect(success!.method).toBe("POST");
expect(JSON.parse(success!.body!.toString())).toEqual({
operationName: "Test",
query: queryString,
variables,
extensions: {
persistedQuery: {
version: VERSION,
sha256Hash: hash,
},
},
});
resolve();
}, reject);
}
);
// https://github.com/apollographql/apollo-client/pull/7456
itAsync("forces POST request when sending full query", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: giveUpResponse })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const link = createPersistedQuery({
sha256,
disable({ operation }) {
operation.setContext({
fetchOptions: {
method: "GET",
},
});
return true;
},
}).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure]] = fetchMock.calls();
expect(failure!.method).toBe("POST");
expect(JSON.parse(failure!.body!.toString())).toEqual({
operationName: "Test",
variables,
extensions: {
persistedQuery: {
version: VERSION,
sha256Hash: hash,
},
},
});
const [, [, success]] = fetchMock.calls();
expect(success!.method).toBe("POST");
expect(JSON.parse(success!.body!.toString())).toEqual({
operationName: "Test",
query: queryString,
variables,
});
resolve();
}, reject);
});
it.each([
["error message", giveUpResponse],
["error code", giveUpResponseWithCode],
] as const)(
"does not try again after receiving NotSupported error (%s)",
(_description, failingResponse) =>
new Promise<void>((resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: failingResponse })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
// mock it again so we can verify it doesn't try anymore
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure]] = fetchMock.calls();
expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();
const [, [, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions
).toBeUndefined();
execute(link, { query, variables }).subscribe((secondResult) => {
expect(secondResult.data).toEqual(data);
const [, , [, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(
queryString
);
expect(
JSON.parse(success!.body!.toString()).extensions
).toBeUndefined();
resolve();
}, reject);
}, reject);
})
);
it.each([
// TODO(fixme): test flake on CI https://github.com/apollographql/apollo-client/issues/11782
// ["error message", giveUpResponse],
["error code", giveUpResponseWithCode],
] as const)(
"clears the cache when receiving NotSupported error (%s)",
async (_description, failingResponse) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: failingResponse })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const hashRefs: WeakRef<String>[] = [];
function hash(query: string) {
const newHash = new String(query);
hashRefs.push(new WeakRef(newHash));
return newHash as string;
}
const persistedLink = createPersistedQuery({ sha256: hash });
await new Promise<void>((complete) =>
execute(persistedLink.concat(createHttpLink()), {
query,
variables,
}).subscribe({ complete })
);
// fetch-mock holds a history of all options it has been called with
// that includes the `signal` option, which (with the native `AbortController`)
// has a reference to the `Request` instance, which will somehow reference our
// hash object
fetchMock.resetHistory();
await expect(hashRefs[0]).toBeGarbageCollected();
}
);
itAsync("works with multiple errors", (resolve, reject) => {
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: multiResponse })),
{ repeat: 1 }
);
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const link = createPersistedQuery({ sha256 }).concat(createHttpLink());
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, failure]] = fetchMock.calls();
expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();
const [, [, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
resolve();
}, reject);
});
describe.each([[400], [500]])("status %s", (status) => {
itAsync(
`handles a ${status} network with a "PERSISTED_QUERY_NOT_FOUND" error and still retries`,
(resolve, reject) => {
let requestCount = 0;
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
// mock it again so we can verify it doesn't try anymore
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 5 }
);
const fetcher = (...args: any[]) => {
if (++requestCount % 2) {
return Promise.resolve({
json: () => Promise.resolve(errorResponseWithCode),
text: () => Promise.resolve(errorResponseWithCode),
status,
});
}
// @ts-expect-error
return global.fetch.apply(null, args);
};
const link = createPersistedQuery({ sha256 }).concat(
createHttpLink({ fetch: fetcher } as any)
);
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
execute(link, { query, variables }).subscribe((secondResult) => {
expect(secondResult.data).toEqual(data);
const [, [, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(
queryString
);
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
resolve();
}, reject);
}, reject);
}
);
it(`will fail on an unrelated ${status} network error, but still send a hash the next request`, async () => {
let failed = false;
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
// mock it again so we can verify it doesn't try anymore
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const fetcher = (...args: any[]) => {
if (!failed) {
failed = true;
return Promise.resolve({
json: () => Promise.resolve("This will blow up"),
text: () => Promise.resolve("THIS WILL BLOW UP"),
status,
});
}
// @ts-expect-error
return global.fetch.apply(null, args);
};
const link = createPersistedQuery({ sha256 }).concat(
createHttpLink({ fetch: fetcher } as any)
);
const failingAttempt = toPromise(execute(link, { query, variables }));
await expect(failingAttempt).rejects.toThrow();
expect(fetchMock.calls().length).toBe(0);
const successfullAttempt = toPromise(execute(link, { query, variables }));
await expect(successfullAttempt).resolves.toEqual({ data });
const [[, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBeUndefined();
expect(
JSON.parse(success!.body!.toString()).extensions.persistedQuery
.sha256Hash
).toBe(hash);
});
itAsync(
`handles ${status} response network error and graphql error without disabling persistedQuery support`,
(resolve, reject) => {
let failed = false;
fetchMock.post(
"/graphql",
() => new Promise((resolve) => resolve({ body: response })),
{ repeat: 1 }
);
const fetcher = (...args: any[]) => {
if (!failed) {
failed = true;
return Promise.resolve({
json: () => Promise.resolve(errorResponse),
text: () => Promise.resolve(errorResponse),
status,
});
}
// @ts-expect-error
return global.fetch.apply(null, args);
};
const link = createPersistedQuery({ sha256 }).concat(
createHttpLink({ fetch: fetcher } as any)
);
execute(link, { query, variables }).subscribe((result) => {
expect(result.data).toEqual(data);
const [[, success]] = fetchMock.calls();
expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);
expect(
JSON.parse(success!.body!.toString()).extensions
).not.toBeUndefined();
resolve();
}, reject);
}
);
});
});