-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathapi.test.ts
More file actions
701 lines (622 loc) · 19.8 KB
/
api.test.ts
File metadata and controls
701 lines (622 loc) · 19.8 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
import {
themeCreate,
themeDelete,
themeDuplicate,
fetchTheme,
fetchThemes,
ThemeParams,
themeUpdate,
themePublish,
fetchChecksums,
bulkUploadThemeAssets,
AssetParams,
deleteThemeAssets,
parseThemeFileContent,
} from './api.js'
import {Operation} from './types.js'
import {ThemeDelete} from '../../../cli/api/graphql/admin/generated/theme_delete.js'
import {ThemeDuplicate} from '../../../cli/api/graphql/admin/generated/theme_duplicate.js'
import {ThemeUpdate} from '../../../cli/api/graphql/admin/generated/theme_update.js'
import {ThemePublish} from '../../../cli/api/graphql/admin/generated/theme_publish.js'
import {ThemeCreate} from '../../../cli/api/graphql/admin/generated/theme_create.js'
import {GetThemeFileChecksums} from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js'
import {ThemeFilesUpsert} from '../../../cli/api/graphql/admin/generated/theme_files_upsert.js'
import {ThemeFilesDelete} from '../../../cli/api/graphql/admin/generated/theme_files_delete.js'
import {GetThemes} from '../../../cli/api/graphql/admin/generated/get_themes.js'
import {GetTheme} from '../../../cli/api/graphql/admin/generated/get_theme.js'
import {adminRequestDoc, supportedApiVersions} from '../api/admin.js'
import {AbortError} from '../error.js'
import {test, vi, expect, describe, beforeEach} from 'vitest'
import {ClientError} from 'graphql-request'
vi.mock('@shopify/cli-kit/node/api/admin')
vi.mock('@shopify/cli-kit/node/system')
vi.stubGlobal('fetch', vi.fn())
const session = {token: 'token', storeFqdn: 'my-shop.myshopify.com', refresh: async () => {}}
const themeAccessSession = {...session, token: 'shptka_token'}
const sessions = {CLI: session, 'Theme Access': themeAccessSession}
const expectedApiOptions = expect.objectContaining({
maxRetryTimeMs: 90000,
useAbortSignal: false,
useNetworkLevelRetry: true,
})
describe('fetchTheme', () => {
test('returns a store theme', async () => {
vi.mocked(adminRequestDoc).mockResolvedValue({
theme: {id: 'gid://shopify/OnlineStoreTheme/123', name: 'store theme 1', role: 'MAIN', processing: false},
})
// When
const theme = await fetchTheme(123, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: GetTheme,
session,
variables: {id: 'gid://shopify/OnlineStoreTheme/123'},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
expect(theme).not.toBeNull()
expect(theme!.id).toEqual(123)
expect(theme!.name).toEqual('store theme 1')
expect(theme!.processing).toBeFalsy()
})
test('returns undefined when a theme is not found', async () => {
const errorResponse = {
status: 200,
errors: [{message: 'Tema não existe'} as any],
}
vi.mocked(adminRequestDoc).mockRejectedValue(new ClientError(errorResponse, {query: ''}))
// When
const theme = await fetchTheme(123, session)
// Then
expect(theme).toBeUndefined()
expect(adminRequestDoc).toHaveBeenCalledWith({
query: GetTheme,
session,
variables: {id: 'gid://shopify/OnlineStoreTheme/123'},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
})
})
describe('fetchThemes', () => {
test('returns store themes', async () => {
// Given
vi.mocked(adminRequestDoc).mockResolvedValue({
themes: {
nodes: [
{id: 'gid://shopify/OnlineStoreTheme/123', name: 'store theme 1', role: 'UNPUBLISHED', processing: false},
{id: 'gid://shopify/OnlineStoreTheme/456', name: 'store theme 2', role: 'MAIN', processing: true},
],
pageInfo: {hasNextPage: false, endCursor: null},
},
})
// When
const themes = await fetchThemes(session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: GetThemes,
session,
variables: {after: null},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
expect(themes).toHaveLength(2)
expect(themes[0]!.id).toEqual(123)
expect(themes[1]!.id).toEqual(456)
expect(themes[0]!.name).toEqual('store theme 1')
expect(themes[1]!.name).toEqual('store theme 2')
expect(themes[0]!.processing).toBeFalsy()
expect(themes[1]!.processing).toBeTruthy()
})
})
describe('fetchChecksums', () => {
test('returns theme checksums', async () => {
// Given
vi.mocked(supportedApiVersions).mockResolvedValue(['2024-10'])
vi.mocked(adminRequestDoc).mockResolvedValue({
theme: {
files: {
nodes: [
{
filename: 'snippets/product-variant-picker.liquid',
checksumMd5: '29e2e56057c3b58c02bc7946d7600481',
},
{
filename: 'templates/404.json',
checksumMd5: 'f14a0bd594f4fee47b13fc09543098ff',
},
{
filename: 'templates/article.json',
checksumMd5: null,
},
],
pageInfo: {hasNextPage: false, endCursor: null},
},
},
})
// When
const id = 123
const checksum = await fetchChecksums(id, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: GetThemeFileChecksums,
session,
variables: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
after: null,
},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
expect(checksum).toHaveLength(3)
expect(checksum[0]!.key).toEqual('snippets/product-variant-picker.liquid')
expect(checksum[1]!.key).toEqual('templates/404.json')
expect(checksum[2]!.key).toEqual('templates/article.json')
expect(checksum[0]!.checksum).toEqual('29e2e56057c3b58c02bc7946d7600481')
expect(checksum[1]!.checksum).toEqual('f14a0bd594f4fee47b13fc09543098ff')
expect(checksum[2]!.checksum).toEqual(null)
})
})
describe('themeCreate', () => {
const id = 123
const name = 'new theme'
const role = 'unpublished'
const params: ThemeParams = {name, role}
test('creates a theme', async () => {
// Given
vi.mocked(adminRequestDoc).mockResolvedValueOnce({
themeCreate: {
theme: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
name,
role,
},
userErrors: [],
},
})
// When
const theme = await themeCreate(params, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeCreate,
session,
variables: {
name: params.name,
source: 'https://cdn.shopify.com/static/online-store/theme-skeleton.zip',
role: 'UNPUBLISHED',
},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
expect(theme).not.toBeNull()
expect(theme!.id).toEqual(id)
expect(theme!.name).toEqual(name)
expect(theme!.role).toEqual(role)
expect(theme!.processing).toBeFalsy()
})
test('does not use skeletonThemeCdn when src is provided', async () => {
// Given
vi.mocked(adminRequestDoc).mockResolvedValueOnce({
themeCreate: {
theme: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
name,
role,
},
userErrors: [],
},
})
// When
const theme = await themeCreate({...params, src: 'https://example.com/theme.zip'}, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeCreate,
session,
variables: {
name: params.name,
source: 'https://example.com/theme.zip',
role: 'UNPUBLISHED',
},
responseOptions: {handleErrors: false},
preferredBehaviour: expectedApiOptions,
})
})
})
describe('themeUpdate', () => {
for (const [sessionType, session] of Object.entries(sessions)) {
test(`updates a theme with graphql with a ${sessionType} session`, async () => {
// Given
const id = 123
const name = 'updated theme'
const role = 'unpublished'
const params: ThemeParams = {name, role}
vi.mocked(adminRequestDoc).mockResolvedValue({
themeUpdate: {
theme: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
name,
role,
},
userErrors: [],
},
})
// When
const theme = await themeUpdate(id, params, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeUpdate,
session,
variables: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
input: {name},
},
preferredBehaviour: expectedApiOptions,
})
expect(theme).not.toBeNull()
expect(theme!.id).toEqual(id)
expect(theme!.name).toEqual(name)
expect(theme!.role).toEqual(role)
})
}
test('no-ops when input hash is empty', async () => {
// Given
const id = 123
const name = 'theme'
const role = 'unpublished'
vi.mocked(adminRequestDoc).mockResolvedValue({
themeUpdate: {
theme: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
name,
role,
},
userErrors: [],
},
})
// When
const theme = await themeUpdate(id, {}, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeUpdate,
session,
variables: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
input: {},
},
preferredBehaviour: expectedApiOptions,
})
expect(theme).not.toBeNull()
expect(theme!.id).toEqual(id)
expect(theme!.name).toEqual(name)
expect(theme!.role).toEqual(role)
})
})
describe('themePublish', () => {
for (const [sessionType, session] of Object.entries(sessions)) {
test(`publish a theme with graphql with a ${sessionType} session`, async () => {
// Given
const id = 123
const name = 'updated theme'
const role = 'live'
vi.mocked(adminRequestDoc).mockResolvedValue({
themePublish: {
theme: {
id: `gid://shopify/OnlineStoreTheme/${id}`,
name,
role,
},
userErrors: [],
},
})
// When
const theme = await themePublish(id, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemePublish,
session,
variables: {id: `gid://shopify/OnlineStoreTheme/${id}`},
preferredBehaviour: expectedApiOptions,
})
expect(theme).not.toBeNull()
expect(theme!.id).toEqual(id)
expect(theme!.name).toEqual(name)
expect(theme!.role).toEqual(role)
})
}
})
describe('deleteThemeAssets', () => {
test('deletes a theme asset', async () => {
// Given
const id = 123
const key = 'snippets/product-variant-picker.liquid'
vi.mocked(adminRequestDoc).mockResolvedValue({
themeFilesDelete: {
deletedThemeFiles: [{filename: key}],
userErrors: [],
},
})
// When
const output = await deleteThemeAssets(id, [key], session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeFilesDelete,
session,
variables: {
themeId: `gid://shopify/OnlineStoreTheme/${id}`,
files: [key],
},
preferredBehaviour: expectedApiOptions,
})
expect(output).toEqual([{key, success: true, operation: 'DELETE'}])
})
test('returns success when attempting to delete nonexistent assets', async () => {
// Given
const id = 123
const key = 'snippets/product-variant-picker.liquid'
vi.mocked(adminRequestDoc).mockResolvedValue({
themeFilesDelete: {
deletedThemeFiles: [{filename: key}],
userErrors: [],
},
})
// When
const output = await deleteThemeAssets(id, [key], session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeFilesDelete,
session,
variables: {
themeId: `gid://shopify/OnlineStoreTheme/${id}`,
files: [key],
},
preferredBehaviour: expectedApiOptions,
})
expect(output).toEqual([{key, success: true, operation: 'DELETE'}])
})
})
describe('themeDelete', () => {
for (const [sessionType, session] of Object.entries(sessions)) {
test(`deletes a theme with graphql with a ${sessionType} session`, async () => {
// Given
const id = 123
vi.mocked(adminRequestDoc).mockResolvedValue({
themeDelete: {
deletedThemeId: 'gid://shopify/OnlineStoreTheme/123',
userErrors: [],
},
})
// When
const response = await themeDelete(id, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeDelete,
session,
variables: {id: `gid://shopify/OnlineStoreTheme/${id}`},
preferredBehaviour: expectedApiOptions,
})
expect(response).toBe(true)
})
}
})
describe('themeDuplicate', () => {
for (const [sessionType, session] of Object.entries(sessions)) {
test(`duplicates a theme with graphql with a ${sessionType} session`, async () => {
// Given
const id = 123
const name = 'duplicate theme'
vi.mocked(adminRequestDoc).mockResolvedValue({
themeDuplicate: {
newTheme: {id: `gid://shopify/OnlineStoreTheme/${id}`, name, role: 'UNPUBLISHED'},
userErrors: [],
},
})
// When
const response = await themeDuplicate(id, name, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeDuplicate,
session,
variables: {id: `gid://shopify/OnlineStoreTheme/${id}`, name},
preferredBehaviour: expectedApiOptions,
responseOptions: {
onResponse: expect.any(Function),
},
})
expect(response).toMatchObject({
theme: {id, name, role: 'unpublished'},
userErrors: [],
requestId: undefined,
})
})
}
})
describe('request errors', () => {
test(`returns AbortError when graphql returns user error`, async () => {
// Given
vi.mocked(adminRequestDoc).mockResolvedValue({
themeDelete: {
deletedThemeId: null,
userErrors: [{message: 'Could not delete theme'}],
},
})
await expect(async () => {
// When
return themeDelete(1, session)
// Then
}).rejects.toThrowError(AbortError)
})
})
describe('bulkUploadThemeAssets', async () => {
test('uploads multiple TEXT and BASE64 assets', async () => {
const id = 123
const assets: AssetParams[] = [
{key: 'snippets/product-variant-picker.liquid', value: 'content'},
{
key: 'templates/404.json',
value: 'to_be_replaced_with_hash',
},
]
vi.mocked(adminRequestDoc).mockResolvedValue({
themeFilesUpsert: {
upsertedThemeFiles: [{filename: 'snippets/product-variant-picker.liquid'}, {filename: 'templates/404.json'}],
userErrors: [],
},
})
// When
const bulkUploadresults = await bulkUploadThemeAssets(id, assets, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeFilesUpsert,
session,
variables: {
themeId: `gid://shopify/OnlineStoreTheme/${id}`,
files: [
{
filename: 'snippets/product-variant-picker.liquid',
body: {value: 'content', type: 'TEXT'},
},
{
filename: 'templates/404.json',
body: {value: 'to_be_replaced_with_hash', type: 'TEXT'},
},
],
},
preferredBehaviour: expect.objectContaining({
maxRetryTimeMs: 90000,
useAbortSignal: false,
useNetworkLevelRetry: true,
}),
})
expect(bulkUploadresults).toEqual([
{
key: 'snippets/product-variant-picker.liquid',
success: true,
operation: Operation.Upload,
},
{
key: 'templates/404.json',
success: true,
operation: Operation.Upload,
},
])
})
test('throws an error when returns userErrors with filenames', async () => {
const id = 123
const assets: AssetParams[] = [
{key: 'snippets/product-variant-picker.liquid', value: 'content'},
{
key: 'templates/404.json',
value: 'to_be_replaced_with_hash',
},
]
vi.mocked(adminRequestDoc).mockResolvedValue({
themeFilesUpsert: {
upsertedThemeFiles: [],
userErrors: [
{filename: 'snippets/product-variant-picker.liquid', message: 'Something went wrong'},
{filename: 'templates/404.json', message: 'Something went wrong'},
],
},
})
// When
const bulkUploadresults = await bulkUploadThemeAssets(id, assets, session)
// Then
expect(adminRequestDoc).toHaveBeenCalledWith({
query: ThemeFilesUpsert,
session,
variables: {
themeId: `gid://shopify/OnlineStoreTheme/${id}`,
files: [
{
filename: 'snippets/product-variant-picker.liquid',
body: {value: 'content', type: 'TEXT'},
},
{
filename: 'templates/404.json',
body: {value: 'to_be_replaced_with_hash', type: 'TEXT'},
},
],
},
preferredBehaviour: expect.objectContaining({
maxRetryTimeMs: 90000,
useAbortSignal: false,
useNetworkLevelRetry: true,
}),
})
expect(bulkUploadresults).toEqual([
{
key: 'snippets/product-variant-picker.liquid',
success: false,
operation: Operation.Upload,
errors: {asset: ['Something went wrong']},
},
{
key: 'templates/404.json',
success: false,
operation: Operation.Upload,
errors: {asset: ['Something went wrong']},
},
])
})
test('throws an error when returns userErrors with no filename', async () => {
const id = 123
const assets: AssetParams[] = [
{key: 'snippets/product-variant-picker.liquid', value: 'content'},
{
key: 'templates/404.json',
value: 'to_be_replaced_with_hash',
},
]
vi.mocked(adminRequestDoc).mockResolvedValue({
themeFilesUpsert: {
upsertedThemeFiles: [],
userErrors: [{message: 'Something went wrong'}],
},
})
await expect(bulkUploadThemeAssets(id, assets, session)).rejects.toThrow(AbortError)
await expect(bulkUploadThemeAssets(id, assets, session)).rejects.toThrow(
'Error uploading theme files: Something went wrong',
)
})
})
describe('parseThemeFileContent', () => {
const normalContent = 'foo'
const base64Content = Buffer.from(normalContent).toString('base64')
describe('when the body type is OnlineStoreThemeFileBodyText', () => {
test('returns the content field as a value', async () => {
const body = {
__typename: 'OnlineStoreThemeFileBodyText' as const,
content: normalContent,
}
const parsedContent = await parseThemeFileContent(body)
expect(parsedContent).toEqual({value: normalContent})
})
})
describe('when the body type is OnlineStoreThemeFileBodyBase64', () => {
test('returns the contentBase64 field as an attachment', async () => {
const body = {
__typename: 'OnlineStoreThemeFileBodyBase64' as const,
contentBase64: base64Content,
}
const parsedContent = await parseThemeFileContent(body)
expect(parsedContent).toEqual({attachment: base64Content})
})
})
describe('when the body type is OnlineStoreThemeFileBodyUrl', () => {
beforeEach(() => {
vi.mocked(fetch).mockResolvedValue(
new Response(normalContent, {
headers: {'Content-Type': 'application/javascript'},
}),
)
})
test('fetches the content from the url and returns it as an attachment', async () => {
const body = {
__typename: 'OnlineStoreThemeFileBodyUrl' as const,
url: 'https://example.com/foo',
}
const parsedContent = await parseThemeFileContent(body)
expect(parsedContent).toEqual({attachment: base64Content})
})
})
})