Adds a product to a custom collection
One script reply has been approved by the moderators Verified

Adds a product to a custom collection.

Created by hugo697 883 days ago Picked 1 time
Submitted by hugo697 Typescript (fetch-only)
Verified 337 days ago
1
type Shopify = {
2
  token: string;
3
  store_name: string;
4
};
5
/**
6
 * Adds a product to a custom collection
7
 * Adds a product to a custom collection.
8
 */
9
export async function main(
10
  auth: Shopify,
11
  api_version: string = "2023-10",
12
  body: {
13
    collect?: {
14
      collection_id?: number;
15
      product_id?: number;
16
      [k: string]: unknown;
17
    };
18
    [k: string]: unknown;
19
  }
20
) {
21
  const url = new URL(
22
    `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/collects.json`
23
  );
24

25
  const response = await fetch(url, {
26
    method: "POST",
27
    headers: {
28
      "Content-Type": "application/json",
29
      "X-Shopify-Access-Token": auth.token,
30
    },
31
    body: JSON.stringify(body),
32
  });
33
  if (!response.ok) {
34
    const text = await response.text();
35
    throw new Error(`${response.status} ${text}`);
36
  }
37
  return await response.json();
38
}
39