Repository navigation
Expand file tree
/
Copy pathgraphql.test.ts
More file actions
895 lines (801 loc) · 27.4 KB
/
Copy pathgraphql.test.ts
File metadata and controls
895 lines (801 loc) · 27.4 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
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
import {graphqlRequest, graphqlRequestDoc} from './graphql.js'
import * as api from '../../../private/node/api.js'
import * as debugRequest from '../../../private/node/api/graphql.js'
import {requestIdsCollection} from '../../../private/node/request-ids.js'
import * as metadata from '../metadata.js'
import * as confStore from '../../../private/node/conf-store.js'
import {inTemporaryDirectory} from '../fs.js'
import {LocalStorage} from '../local-storage.js'
import {ConfSchema, GraphQLRequestKey} from '../../../private/node/conf-store.js'
import {nonRandomUUID, sha256} from '../crypto.js'
import {CLI_KIT_VERSION} from '../../common/version.js'
import * as system from '../system.js'
import {test, vi, describe, expect, beforeEach, beforeAll, afterAll, afterEach} from 'vitest'
import {TypedDocumentNode} from '@graphql-typed-document-node/core'
import {parse} from 'graphql'
import {setupServer} from 'msw/node'
import {graphql, HttpResponse} from 'msw'
let mockedRequestId = 'request-id-123'
vi.spyOn(debugRequest, 'debugLogRequestInfo').mockResolvedValue(undefined)
vi.spyOn(system, 'sleep').mockImplementation(async () => {})
const mockedAddress = 'https://shopify.example/graphql'
const mockVariables = {some: 'variables'}
const mockToken = 'token'
const mockedAddedHeaders = {some: 'header'}
beforeEach(async () => {
requestIdsCollection.clear()
})
const mockApi = graphql.link('https://shopify.example/graphql')
const handlers = [
mockApi.query('QueryName', ({query}) => {
return HttpResponse.json(
{
data: {
QueryName: {example: 'hello'},
},
extensions: {
cost: {
actualQueryCost: 10,
throttleStatus: {
restoreRate: 10000,
},
},
},
},
{
headers: {
'x-request-id': mockedRequestId,
},
},
)
}),
mockApi.query('Fails', () => {
return HttpResponse.json(
{
errors: [
{
message: `Cannot do the thing`,
},
],
},
{
headers: {
'x-request-id': 'failed-request-id',
},
},
)
}),
mockApi.query('FailsWithUnauthorized', () => {
return HttpResponse.json(
{
errors: [
{
message: `not authorized`,
},
],
},
{
status: 401,
headers: {
'x-request-id': 'failed-request-id',
},
},
)
}),
mockApi.query('FailsWithUnauthorizedAndNoBody', () => {
// A gateway's 401 has no GraphQL body, so the typed `HttpResponse.json` doesn't fit here.
return new HttpResponse(null, {
status: 401,
headers: {
'x-request-id': 'unauthorized-request-id',
},
})
}),
mockApi.query('FailsWithBadRequest', () => {
return HttpResponse.json(
{
errors: [
{
message: `bad request`,
},
],
},
{
status: 400,
headers: {
'x-request-id': 'failed-request-id',
},
},
)
}),
mockApi.mutation('MutationName', ({query, variables}) => {
return HttpResponse.json(
{
data: {
MutationName: {example: variables.some},
},
},
{
headers: {
'x-request-id': mockedRequestId,
},
},
)
}),
]
const server = setupServer(...handlers)
beforeAll(() => server.listen({onUnhandledRequest: 'error'}))
afterAll(() => server.close())
afterEach(() => {
server.resetHandlers()
server.events.removeAllListeners()
})
describe('graphqlRequest', () => {
test.each([false, true])('retries a throttled nullable query (typed document: %s)', async (useTypedDocument) => {
const receivedVariables: unknown[] = []
const data = {appsConnection: {edges: [{node: {id: 'app-123'}}]}}
server.use(
mockApi.query('ListApps', ({variables}) => {
receivedVariables.push(variables)
if (receivedVariables.length === 1) {
return HttpResponse.json(
{
data: {appsConnection: null},
errors: [{message: 'Throttled', path: ['appsConnection'], extensions: {code: 'THROTTLED'}}],
},
{headers: {'Retry-After': '0'}},
)
}
return HttpResponse.json({data})
}),
)
const query =
'query ListApps($query: String) { appsConnection(query: $query, first: 50) { edges { node { id } } } }'
const variables = {query: 'title:example'}
const options = {api: 'mockApi', url: mockedAddress, variables}
const result = useTypedDocument
? await graphqlRequestDoc({...options, query: parse(query)})
: await graphqlRequest({...options, query})
expect(result).toEqual(data)
expect(receivedVariables).toEqual([variables, variables])
})
test('retries only the throttled mutation request with its original variables', async () => {
const receivedVariables: unknown[] = []
server.use(
mockApi.mutation('CreateAppVersion', ({variables}) => {
receivedVariables.push(variables)
if (receivedVariables.length === 1) {
return HttpResponse.json(
{errors: [{message: 'Throttled', extensions: {code: 'THROTTLED'}}]},
{headers: {'Retry-After': '0'}},
)
}
return HttpResponse.json({data: {appVersionCreate: {version: {id: 'created-version'}}}})
}),
)
const variables = {appId: 'test-app'}
const result = await graphqlRequest({
api: 'mockApi',
url: mockedAddress,
query: 'mutation CreateAppVersion($appId: ID!) { appVersionCreate(appId: $appId) { version { id } } }',
variables,
})
expect(result).toEqual({appVersionCreate: {version: {id: 'created-version'}}})
expect(receivedVariables).toEqual([variables, variables])
})
test('does not repeat a mutation when a throttled response contains partial data', async () => {
let requestCount = 0
server.use(
mockApi.mutation('CreateAppVersion', () => {
requestCount++
return HttpResponse.json(
{
data: {appVersionCreate: {version: {id: 'created-version'}}},
errors: [{message: 'Throttled', extensions: {code: 'THROTTLED'}}],
},
{headers: {'Retry-After': '0'}},
)
}),
)
await expect(
graphqlRequest({
api: 'mockApi',
url: mockedAddress,
query: 'mutation CreateAppVersion { appVersionCreate { version { id } } }',
}),
).rejects.toThrow('Throttled')
expect(requestCount).toBe(1)
})
test('calls debugLogRequestInfo once', async () => {
let headers: any
server.events.on('request:start', ({request}) => {
headers = {}
request.headers.forEach((value, key) => {
headers[key] = value
})
})
// When
const res = await graphqlRequest({
query: 'query QueryName { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
})
expect(debugRequest.debugLogRequestInfo).toHaveBeenCalledOnce()
// user agents varies a lot
const {'user-agent': userAgent, 'sec-ch-ua-platform': _platform, ...otherHeaders} = headers
expect(otherHeaders).toMatchInlineSnapshot(`
{
"accept": "*/*",
"accept-encoding": "gzip,deflate",
"authorization": "Bearer token",
"connection": "close",
"content-length": "100",
"content-type": "application/json",
"host": "shopify.example",
"keep-alive": "timeout=30",
"some": "header",
"x-shopify-access-token": "Bearer token",
}
`)
expect(res).toMatchInlineSnapshot(`
{
"QueryName": {
"example": "hello",
},
}
`)
expect(userAgent).toMatch(new RegExp(`Shopify CLI; v=${CLI_KIT_VERSION}`))
})
test('Logs the request ids to metadata and requestIdCollection', async () => {
// Given
const metadataSpyOn = vi.spyOn(metadata, 'addPublicMetadata').mockImplementation(async () => {})
// When
await graphqlRequest({
query: 'query QueryName { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
})
mockedRequestId = 'request-id-456'
await graphqlRequest({
query: 'query QueryName { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
})
// Then
expect(requestIdsCollection.getRequestIds()).toEqual(['request-id-123', 'request-id-456'])
expect(metadataSpyOn).toHaveBeenCalledTimes(2)
expect(metadataSpyOn.mock.calls[0]![0]()).toEqual({cmd_all_last_graphql_request_id: 'request-id-123'})
expect(metadataSpyOn.mock.calls[1]![0]()).toEqual({cmd_all_last_graphql_request_id: 'request-id-456'})
})
test('calls onResponseHandler', async () => {
// When
let data
const onResponseHandler = vi.fn().mockImplementation((res) => {
data = res.data
})
await graphqlRequest({
query: 'query QueryName { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
responseOptions: {
onResponse: onResponseHandler,
},
})
expect(data).toMatchInlineSnapshot(`
{
"QueryName": {
"example": "hello",
},
}
`)
})
test('logs the last request id from a failed request', async () => {
const metadataSpyOn = vi.spyOn(metadata, 'addPublicMetadata').mockImplementation(async () => {})
const res = graphqlRequest({
query: 'query Fails { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
})
await expect(res).rejects.toThrow('Cannot do the thing')
expect(metadataSpyOn).toHaveBeenCalledTimes(1)
expect(metadataSpyOn.mock.calls[0]![0]()).toMatchInlineSnapshot(`
{
"cmd_all_last_graphql_request_id": "failed-request-id",
}
`)
})
test('Fails without retry when unauthorized and no token refresh function is provided', async () => {
const res = graphqlRequest({
query: 'query FailsWithUnauthorized { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
})
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
await expect(res).rejects.toThrow('not authorized')
expect(requestCount).toBe(1)
})
test('Fails without retry when unauthorized and a token refresh function cannot refresh the token', async () => {
const res = graphqlRequest({
query: 'query FailsWithUnauthorized { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: undefined})},
})
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
await expect(res).rejects.toThrow('not authorized')
expect(requestCount).toBe(1)
})
test('Retries once with refreshed token when unauthorized and refresh succeeds', async () => {
const res = graphqlRequest({
query: 'query FailsWithUnauthorized { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: 'refreshed-token'})},
})
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
await expect(res).rejects.toThrow('not authorized')
expect(requestCount).toBe(2)
})
describe('a 401 that survives the token refresh', () => {
const query = 'query FailsWithUnauthorizedAndNoBody { example(secret: $secret) }'
const variables = {secret: 'do-not-print-me'}
test('reports the status without the request when no token refresh function is provided', async () => {
const res = graphqlRequest({query, api: 'mockApi', url: mockedAddress, token: mockToken, variables})
await expect(res).rejects.toMatchObject({
statusCode: 401,
message:
'The mockApi GraphQL API responded unsuccessfully with the HTTP status 401.\n\nRequest ID: unauthorized-request-id',
})
await expect(res).rejects.not.toThrow(/do-not-print-me|example\(secret/)
})
test('reports the status without the request when the token cannot be refreshed', async () => {
const res = graphqlRequest({
query,
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables,
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: undefined})},
})
await expect(res).rejects.toMatchObject({statusCode: 401})
await expect(res).rejects.not.toThrow(/do-not-print-me|example\(secret/)
})
test('reports the status without the request when the refreshed token is rejected too', async () => {
const res = graphqlRequest({
query,
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables,
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: 'refreshed-token'})},
})
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
await expect(res).rejects.toMatchObject({statusCode: 401})
await expect(res).rejects.not.toThrow(/do-not-print-me|example\(secret/)
expect(requestCount).toBe(2)
})
test('keeps the raw error when the caller handles errors itself', async () => {
const res = graphqlRequest({
query,
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables,
responseOptions: {handleErrors: false},
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: 'refreshed-token'})},
})
await expect(res).rejects.toMatchObject({response: {status: 401}})
})
})
test('Fails without retry when bad request when unauthorized handler is provided', async () => {
const res = graphqlRequest({
query: 'query FailsWithBadRequest { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
responseOptions: {handleErrors: false},
unauthorizedHandler: {type: 'token_refresh', handler: async () => ({token: 'refreshed-token'})},
})
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
await expect(res).rejects.toThrow('bad request')
expect(requestCount).toBe(1)
})
})
describe('graphqlRequestDoc', () => {
test('converts document before querying', async () => {
// Given
const document = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: {kind: 'Name', value: 'QueryName'},
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
name: {kind: 'Name', value: 'example'},
},
],
},
},
],
} as unknown as TypedDocumentNode<unknown, unknown>
// When
const res = await graphqlRequestDoc({
query: document,
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
})
expect(res).toMatchInlineSnapshot(`
{
"QueryName": {
"example": "hello",
},
}
`)
expect(debugRequest.debugLogRequestInfo).toHaveBeenCalledWith(
'mockApi',
`query QueryName {
example
}`,
'https://shopify.example/graphql',
mockVariables,
expect.anything(),
)
})
test('applies rate limit restoration', async () => {
const document = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: {kind: 'Name', value: 'QueryName'},
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
name: {kind: 'Name', value: 'example'},
},
],
},
},
],
} as unknown as TypedDocumentNode<unknown, unknown>
// When
const res = await graphqlRequestDoc({
query: document,
api: 'mockApi',
url: mockedAddress,
token: mockToken,
addedHeaders: mockedAddedHeaders,
variables: mockVariables,
autoRateLimitRestore: true,
})
expect(res).toMatchInlineSnapshot(`
{
"QueryName": {
"example": "hello",
},
}
`)
expect(system.sleep).toHaveBeenCalledWith(0.001)
})
})
describe('sanitizeVariables', () => {
test('masks sensitive data at the top level', () => {
const variables = {
apiKey: 'secret-key',
normalField: 'normal-value',
serialized_script: 'sensitive-script',
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.apiKey).toBe('*****')
expect(parsed.normalField).toBe('normal-value')
expect(parsed.serialized_script).toBe('*****')
})
test('masks sensitive data in deeply nested objects', () => {
const variables = {
level1: {
apiKey: 'secret-key',
level2: {
serialized_script: 'sensitive-script',
normal: 'normal-value',
},
},
topLevel: 'normal',
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.level1.apiKey).toBe('*****')
expect(parsed.level1.level2.serialized_script).toBe('*****')
expect(parsed.level1.level2.normal).toBe('normal-value')
expect(parsed.topLevel).toBe('normal')
})
test('handles arrays correctly', () => {
const variables = {
items: [{apiKey: 'secret1'}, {apiKey: 'secret2'}, {normal: 'value'}],
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.items[0].apiKey).toBe('*****')
expect(parsed.items[1].apiKey).toBe('*****')
expect(parsed.items[2].normal).toBe('value')
})
test('does not change primitive values', () => {
const variables = {
number: 123,
string: 'normal',
boolean: true,
null: null,
undefined,
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.number).toBe(123)
expect(parsed.string).toBe('normal')
expect(parsed.boolean).toBe(true)
expect(parsed.null).toBe(null)
expect(parsed.undefined).toBe(undefined)
})
test('hides values in json string', () => {
const variables = {
json: '{"api_version": 1, "serialized_script": "ddddddddd"}',
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.json).toBe('{"api_version":1,"serialized_script":"*****"}')
})
test('handling invalid json', () => {
const variables = {
json: '{"api_version": 1',
}
const result = debugRequest.sanitizeVariables(variables)
const parsed = JSON.parse(result)
expect(parsed.json).toBe('{"api_version": 1')
})
})
describe('graphqlRequest with caching', () => {
test('uses cache when TTL is provided', async () => {
vi.useFakeTimers()
await inTemporaryDirectory(async (dir) => {
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
const cacheStore = new LocalStorage<ConfSchema>({projectName: 'test', cwd: dir})
const mutationHash = nonRandomUUID('mutation MutationName($some: String!) { example }')
const firstVariablesHash = nonRandomUUID(JSON.stringify(mockVariables))
const otherVariablesHash = nonRandomUUID(JSON.stringify({...mockVariables, some: 'new-value'}))
// make first request
const firstRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: mockVariables,
cacheOptions: {
cacheTTL: {hours: 1},
cacheExtraKey: 'extra',
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(firstRes).resolves.toEqual({MutationName: {example: 'variables'}})
expect(requestCount).toBe(1)
// repeated request uses cache
const secondRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: mockVariables,
cacheOptions: {
cacheTTL: {hours: 1},
cacheExtraKey: 'extra',
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(secondRes).resolves.toEqual({MutationName: {example: 'variables'}})
expect(requestCount).toBe(1)
// variable changes break the cache
const thirdRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: {...mockVariables, some: 'new-value'},
cacheOptions: {
cacheTTL: {hours: 1},
cacheExtraKey: 'extra',
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(thirdRes).resolves.toEqual({MutationName: {example: 'new-value'}})
expect(requestCount).toBe(2)
// extra key breaks the cache
const fourthRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: {...mockVariables, some: 'new-value'},
cacheOptions: {
cacheTTL: {hours: 1},
cacheExtraKey: 'other-extra',
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(fourthRes).resolves.toEqual({MutationName: {example: 'new-value'}})
expect(requestCount).toBe(3)
// fast-forward by an hour
await vi.advanceTimersByTimeAsync(1000 * 60 * 60)
const fifthRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: {...mockVariables, some: 'new-value'},
cacheOptions: {
cacheTTL: {hours: 1},
cacheExtraKey: 'other-extra',
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(fifthRes).resolves.toEqual({MutationName: {example: 'new-value'}})
expect(requestCount).toBe(4)
// no extra breaks the cache
const sixthRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: {...mockVariables, some: 'new-value'},
cacheOptions: {
cacheTTL: {hours: 1},
cacheStore,
},
})
await vi.runAllTimersAsync()
await expect(sixthRes).resolves.toEqual({MutationName: {example: 'new-value'}})
expect(requestCount).toBe(5)
// finally, no cache options means no cache
const seventhRes = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: {...mockVariables, some: 'new-value'},
})
await vi.runAllTimersAsync()
await expect(seventhRes).resolves.toEqual({MutationName: {example: 'new-value'}})
expect(requestCount).toBe(6)
const principalHash = sha256(JSON.stringify([mockedAddress, mockToken])).toString('hex')
const firstKey: GraphQLRequestKey = `q-${mutationHash}-${firstVariablesHash}-${CLI_KIT_VERSION}-${principalHash}-extra`
const withOtherVariablesKey: GraphQLRequestKey = `q-${mutationHash}-${otherVariablesHash}-${CLI_KIT_VERSION}-${principalHash}-extra`
const withOtherExtraKey: GraphQLRequestKey = `q-${mutationHash}-${otherVariablesHash}-${CLI_KIT_VERSION}-${principalHash}-other-extra`
const noExtraKey: GraphQLRequestKey = `q-${mutationHash}-${otherVariablesHash}-${CLI_KIT_VERSION}-${principalHash}-`
expect(cacheStore.get('cache')![firstKey]).toEqual({
value: '{"MutationName":{"example":"variables"}}',
timestamp: expect.any(Number),
})
expect(cacheStore.get('cache')![withOtherVariablesKey]).toEqual({
value: '{"MutationName":{"example":"new-value"}}',
timestamp: expect.any(Number),
})
expect(cacheStore.get('cache')![withOtherExtraKey]).toEqual({
value: '{"MutationName":{"example":"new-value"}}',
timestamp: expect.any(Number),
})
expect(cacheStore.get('cache')![noExtraKey]).toEqual({
value: '{"MutationName":{"example":"new-value"}}',
timestamp: expect.any(Number),
})
expect(Object.keys(cacheStore.get('cache')!).length).toBe(4)
})
vi.useRealTimers()
})
test('does not share a cached response across tokens or endpoints', async () => {
vi.useFakeTimers()
await inTemporaryDirectory(async (dir) => {
let requestCount = 0
server.events.on('request:start', () => {
requestCount++
})
const cacheStore = new LocalStorage<ConfSchema>({projectName: 'test', cwd: dir})
const cachedRequest = async (options: {url: string; token: string}) => {
const response = graphqlRequest({
query: 'mutation MutationName($some: String!) { example }',
api: 'mockApi',
url: options.url,
token: options.token,
variables: mockVariables,
cacheOptions: {cacheTTL: {hours: 1}, cacheStore},
})
await vi.runAllTimersAsync()
return response
}
// Given a cached response for one token and endpoint
await expect(cachedRequest({url: mockedAddress, token: mockToken})).resolves.toEqual({
MutationName: {example: 'variables'},
})
expect(requestCount).toBe(1)
// When the same query and variables are sent with another token, or to another endpoint
await cachedRequest({url: mockedAddress, token: 'other-token'})
await cachedRequest({url: `${mockedAddress}?other-endpoint=1`, token: mockToken})
// Then each one is sent to the API instead of reading the first response
expect(requestCount).toBe(3)
// And a repeated request with the original token and endpoint still uses its own cache entry
await cachedRequest({url: mockedAddress, token: mockToken})
expect(requestCount).toBe(3)
// And the raw tokens are not part of any cache key
const keys = Object.keys(cacheStore.get('cache')!)
expect(keys.length).toBe(3)
for (const key of keys) {
expect(key).not.toContain(mockToken)
expect(key).not.toContain('other-token')
}
})
vi.useRealTimers()
})
test('skips cache when no TTL is provided', async () => {
const retryAwareSpy = vi
.spyOn(api, 'retryAwareRequest')
.mockImplementation(async () => ({status: 200, headers: new Headers()}))
const cacheRetrieveSpy = vi.spyOn(confStore, 'cacheRetrieveOrRepopulate')
// When
await graphqlRequest({
query: 'query QueryName { example }',
api: 'mockApi',
url: mockedAddress,
token: mockToken,
variables: mockVariables,
})
// Then
expect(cacheRetrieveSpy).not.toHaveBeenCalled()
expect(retryAwareSpy).toHaveBeenCalled()
})
})