Retrieves a count of products

Retrieves a count of products.

Script shopify Verified

by hugo697 ยท 11/8/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 396 days ago
1
type Shopify = {
2
  token: string;
3
  store_name: string;
4
};
5
/**
6
 * Retrieves a count of products
7
 * Retrieves a count of products.
8
 */
9
export async function main(
10
  auth: Shopify,
11
  api_version: string = "2023-10",
12
  vendor: string | undefined,
13
  product_type: string | undefined,
14
  collection_id: string | undefined,
15
  created_at_min: string | undefined,
16
  created_at_max: string | undefined,
17
  updated_at_min: string | undefined,
18
  updated_at_max: string | undefined,
19
  published_at_min: string | undefined,
20
  published_at_max: string | undefined,
21
  published_status: string | undefined
22
) {
23
  const url = new URL(
24
    `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/products/count.json`
25
  );
26
  for (const [k, v] of [
27
    ["vendor", vendor],
28
    ["product_type", product_type],
29
    ["collection_id", collection_id],
30
    ["created_at_min", created_at_min],
31
    ["created_at_max", created_at_max],
32
    ["updated_at_min", updated_at_min],
33
    ["updated_at_max", updated_at_max],
34
    ["published_at_min", published_at_min],
35
    ["published_at_max", published_at_max],
36
    ["published_status", published_status],
37
  ]) {
38
    if (v !== undefined && v !== "") {
39
      url.searchParams.append(k, v);
40
    }
41
  }
42
  const response = await fetch(url, {
43
    method: "GET",
44
    headers: {
45
      "X-Shopify-Access-Token": auth.token,
46
    },
47
    body: undefined,
48
  });
49
  if (!response.ok) {
50
    const text = await response.text();
51
    throw new Error(`${response.status} ${text}`);
52
  }
53
  return await response.json();
54
}
55