1 | |
2 |
|
3 | |
4 | * List Discount Codes |
5 | * List code discounts (basic, buy X get Y, free shipping and app discounts), filtered with Shopify's search syntax (e.g. `status:active`, `discount_type:percentage`, `title:'Summer sale'`). Returns one page; pass pageInfo.endCursor as after for the next. Needs the read_discounts scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | query: string | undefined, |
10 | sort_key: |
11 | | "CREATED_AT" |
12 | | "UPDATED_AT" |
13 | | "STARTS_AT" |
14 | | "ENDS_AT" |
15 | | "TITLE" |
16 | | "ID" |
17 | | "RELEVANCE" |
18 | | undefined, |
19 | reverse: boolean | undefined, |
20 | first: number | undefined, |
21 | after: string | undefined |
22 | ) { |
23 | const response = await fetch( |
24 | `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`, |
25 | { |
26 | method: "POST", |
27 | headers: { |
28 | "X-Shopify-Access-Token": auth.token, |
29 | "Content-Type": "application/json", |
30 | Accept: "application/json", |
31 | }, |
32 | body: JSON.stringify({ |
33 | query: `query ($first: Int!, $after: String, $query: String, $sortKey: DiscountSortKeys, $reverse: Boolean) { discountNodes(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { id discount { __typename ... on DiscountCodeBasic { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 10) { nodes { id code } } } ... on DiscountCodeBxgy { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 10) { nodes { id code } } } ... on DiscountCodeFreeShipping { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 10) { nodes { id code } } } ... on DiscountCodeApp { title status startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 10) { nodes { id code } } } } } pageInfo { hasNextPage endCursor } } }`, |
34 | variables: { |
35 | first: first || 50, |
36 | after: after || undefined, |
37 | query: query ? `method:code ${query}` : "method:code", |
38 | sortKey: sort_key || undefined, |
39 | reverse: reverse || undefined, |
40 | }, |
41 | }), |
42 | } |
43 | ) |
44 |
|
45 | if (!response.ok) { |
46 | throw new Error(`${response.status} ${await response.text()}`) |
47 | } |
48 |
|
49 | const { data, errors } = await response.json() |
50 | if (errors) { |
51 | throw new Error(JSON.stringify(errors)) |
52 | } |
53 |
|
54 | return data.discountNodes |
55 | } |
56 |
|