1 | |
2 |
|
3 | |
4 | * Add Discount Codes (Batch) |
5 | * Add up to 250 extra redeem codes to an existing code discount (numeric ID or DiscountCodeNode GID). Runs asynchronously: the returned bulkCreation has done=false at first; poll it with Get Discount Code (or GraphQL Query on discountRedeemCodeBulkCreation) to see importedCount and failedCount. Needs the write_discounts scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | discount_id: string, |
10 | codes: string[] |
11 | ) { |
12 | const id = discount_id.startsWith("gid://") |
13 | ? discount_id |
14 | : `gid://shopify/DiscountCodeNode/${discount_id}` |
15 |
|
16 | const response = await fetch( |
17 | `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`, |
18 | { |
19 | method: "POST", |
20 | headers: { |
21 | "X-Shopify-Access-Token": auth.token, |
22 | "Content-Type": "application/json", |
23 | Accept: "application/json", |
24 | }, |
25 | body: JSON.stringify({ |
26 | query: `mutation ($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) { discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) { bulkCreation { id done codesCount importedCount failedCount createdAt } userErrors { field message } } }`, |
27 | variables: { discountId: id, codes: codes.map((code) => ({ code })) }, |
28 | }), |
29 | } |
30 | ) |
31 |
|
32 | if (!response.ok) { |
33 | throw new Error(`${response.status} ${await response.text()}`) |
34 | } |
35 |
|
36 | const { data, errors } = await response.json() |
37 | if (errors) { |
38 | throw new Error(JSON.stringify(errors)) |
39 | } |
40 | if (data.discountRedeemCodeBulkAdd.userErrors.length) { |
41 | throw new Error(JSON.stringify(data.discountRedeemCodeBulkAdd.userErrors)) |
42 | } |
43 |
|
44 | return data.discountRedeemCodeBulkAdd |
45 | } |
46 |
|