1 | |
2 |
|
3 | |
4 | * Create Custom Collection |
5 | * Create a manual collection, optionally with an initial list of products (numeric IDs or GIDs). The collection is created unpublished; publish it to a sales channel to show it to customers. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | title: string, |
10 | product_ids: string[] | undefined, |
11 | description_html: string | undefined, |
12 | handle: string | undefined, |
13 | image_url: string | undefined, |
14 | sort_order: |
15 | | "MANUAL" |
16 | | "BEST_SELLING" |
17 | | "ALPHA_ASC" |
18 | | "ALPHA_DESC" |
19 | | "PRICE_ASC" |
20 | | "PRICE_DESC" |
21 | | "CREATED" |
22 | | "CREATED_DESC" |
23 | | undefined |
24 | ) { |
25 | const response = await fetch( |
26 | `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`, |
27 | { |
28 | method: "POST", |
29 | headers: { |
30 | "X-Shopify-Access-Token": auth.token, |
31 | "Content-Type": "application/json", |
32 | Accept: "application/json", |
33 | }, |
34 | body: JSON.stringify({ |
35 | query: `mutation ($collection: CollectionCreateInput!) { collectionCreate(collection: $collection) { collection { id legacyResourceId title handle descriptionHtml sortOrder productsCount { count } sources { id title } } userErrors { field message } } }`, |
36 | variables: { |
37 | collection: { |
38 | title, |
39 | descriptionHtml: description_html || undefined, |
40 | handle: handle || undefined, |
41 | image: image_url ? { src: image_url } : undefined, |
42 | sortOrder: sort_order || undefined, |
43 | sources: product_ids?.length |
44 | ? [ |
45 | { |
46 | source: { |
47 | title, |
48 | inclusion: { |
49 | selections: product_ids.map((id) => ({ |
50 | productId: id.startsWith("gid://") |
51 | ? id |
52 | : `gid://shopify/Product/${id}`, |
53 | })), |
54 | }, |
55 | }, |
56 | }, |
57 | ] |
58 | : undefined, |
59 | }, |
60 | }, |
61 | }), |
62 | } |
63 | ) |
64 |
|
65 | if (!response.ok) { |
66 | throw new Error(`${response.status} ${await response.text()}`) |
67 | } |
68 |
|
69 | const { data, errors } = await response.json() |
70 | if (errors) { |
71 | throw new Error(JSON.stringify(errors)) |
72 | } |
73 | if (data.collectionCreate.userErrors.length) { |
74 | throw new Error(JSON.stringify(data.collectionCreate.userErrors)) |
75 | } |
76 |
|
77 | return data.collectionCreate |
78 | } |
79 |
|