1 | |
2 |
|
3 | |
4 | * Create Smart Collection |
5 | * Create a collection whose products are picked automatically by conditions. Each condition is one object keyed by its type, e.g. {"productTag": {"relation": "TAGGED_WITH", "values": ["sale"], "matchType": "ANY"}}, {"productVendor": {"relation": "EQUALS", "values": ["Acme"], "matchType": "ANY"}}, {"variantPrice": {"relation": "LESS_THAN", "value": {"amount": "20", "currencyCode": "USD"}}}. Types: productTag, productTitle, productType, productVendor, productStatus, productCategory, variantTitle, variantPrice, variantCompareAtPrice, variantInventory, variantWeight, metafield*. The collection is created unpublished. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | title: string, |
10 | conditions: { [key: string]: any }[], |
11 | match_type: "ALL" | "ANY" | undefined, |
12 | description_html: string | undefined, |
13 | handle: string | undefined, |
14 | sort_order: |
15 | | "BEST_SELLING" |
16 | | "ALPHA_ASC" |
17 | | "ALPHA_DESC" |
18 | | "PRICE_ASC" |
19 | | "PRICE_DESC" |
20 | | "CREATED" |
21 | | "CREATED_DESC" |
22 | | "MANUAL" |
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 ... on CollectionConditionsSource { inclusion { matchType conditions { __typename id } } } } } userErrors { field message } } }`, |
36 | variables: { |
37 | collection: { |
38 | title, |
39 | descriptionHtml: description_html || undefined, |
40 | handle: handle || undefined, |
41 | sortOrder: sort_order || undefined, |
42 | sources: [ |
43 | { |
44 | source: { |
45 | title, |
46 | inclusion: { matchType: match_type || "ALL", conditions }, |
47 | }, |
48 | }, |
49 | ], |
50 | }, |
51 | }, |
52 | }), |
53 | } |
54 | ) |
55 |
|
56 | if (!response.ok) { |
57 | throw new Error(`${response.status} ${await response.text()}`) |
58 | } |
59 |
|
60 | const { data, errors } = await response.json() |
61 | if (errors) { |
62 | throw new Error(JSON.stringify(errors)) |
63 | } |
64 | if (data.collectionCreate.userErrors.length) { |
65 | throw new Error(JSON.stringify(data.collectionCreate.userErrors)) |
66 | } |
67 |
|
68 | return data.collectionCreate |
69 | } |
70 |
|