1 | |
2 |
|
3 | |
4 | * Get Discount Code |
5 | * Get a code discount by one of its redeem codes (e.g. `SUMMER10`) or by its ID (numeric ID or DiscountCodeNode GID). Returns its settings and up to 50 of its codes. Needs the read_discounts scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | code: string | undefined, |
10 | discount_id: string | undefined |
11 | ) { |
12 | if (!code && !discount_id) { |
13 | throw new Error("Pass either code or discount_id") |
14 | } |
15 | const id = discount_id |
16 | ? discount_id.startsWith("gid://") |
17 | ? discount_id |
18 | : `gid://shopify/DiscountCodeNode/${discount_id}` |
19 | : undefined |
20 |
|
21 | const response = await fetch( |
22 | `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`, |
23 | { |
24 | method: "POST", |
25 | headers: { |
26 | "X-Shopify-Access-Token": auth.token, |
27 | "Content-Type": "application/json", |
28 | Accept: "application/json", |
29 | }, |
30 | body: JSON.stringify({ |
31 | query: `query ($id: ID!, $code: String!, $byId: Boolean!) { byId: discountNode(id: $id) @include(if: $byId) { id discount { __typename ...B ...X ...S ...A } } byCode: codeDiscountNodeByCode(code: $code) @skip(if: $byId) { id discount: codeDiscount { __typename ...B ...X ...S ...A } } } fragment B on DiscountCodeBasic { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 50) { nodes { id code asyncUsageCount } } } fragment X on DiscountCodeBxgy { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 50) { nodes { id code asyncUsageCount } } } fragment S on DiscountCodeFreeShipping { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 50) { nodes { id code asyncUsageCount } } } fragment A on DiscountCodeApp { title status startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer createdAt updatedAt codesCount { count } codes(first: 50) { nodes { id code asyncUsageCount } } }`, |
32 | variables: { |
33 | id: id || "gid://shopify/DiscountCodeNode/0", |
34 | code: code || "", |
35 | byId: !!id, |
36 | }, |
37 | }), |
38 | } |
39 | ) |
40 |
|
41 | if (!response.ok) { |
42 | throw new Error(`${response.status} ${await response.text()}`) |
43 | } |
44 |
|
45 | const { data, errors } = await response.json() |
46 | if (errors) { |
47 | throw new Error(JSON.stringify(errors)) |
48 | } |
49 |
|
50 | return id ? data.byId : data.byCode |
51 | } |
52 |
|