0
Search Segments
One script reply has been approved by the moderators Verified

Get information about segments of a specific list.

Created by adam186 486 days ago Viewed 2371 times
0
Submitted by adam186 Deno
Verified 486 days ago
1
/**
2
 * @param fields *(optional)* A list of fields to return in the response.
3
 * Reference parameters of sub-objects with dot notation.
4
 *
5
 * @param exclude_fields *(optional)* A list of fields to exclude from the response.
6
 * Reference parameters of sub-objects with dot notation. If both `fields` and `exclude_fields`
7
 * are present, then only `exclude_fields` will be used.
8
 *
9
 * @param since_created_at *(optional)* Uses ISO 8601 time format: `2022-10-21T15:41:36+00:00`.
10
 * @param before_created_at *(optional)* Uses ISO 8601 time format: `2022-10-21T15:41:36+00:00`.
11
 * @param since_updated_at *(optional)* Uses ISO 8601 time format: `2022-10-21T15:41:36+00:00`.
12
 * @param before_updated_at *(optional)* Uses ISO 8601 time format: `2022-10-21T15:41:36+00:00`.
13
 */
14
type Mailchimp = {
15
  api_key: string;
16
  server: string;
17
};
18
export async function main(
19
  auth: Mailchimp,
20
  list_id: string,
21
  fields?: string[],
22
  exclude_fields?: string[],
23
  count?: number,
24
  offset?: number,
25
  type?: string,
26
  since_created_at?: string,
27
  before_created_at?: string,
28
  since_updated_at?: string,
29
  before_updated_at?: string,
30
  include_cleaned?: boolean,
31
  include_transactional?: boolean,
32
  include_unsubscribed?: boolean,
33
) {
34
  const url = new URL(
35
    `https://${auth.server}.api.mailchimp.com/3.0/lists/${list_id}/segments`,
36
  );
37
  const params = {
38
    fields,
39
    exclude_fields,
40
    count,
41
    offset,
42
    type,
43
    since_created_at,
44
    before_created_at,
45
    since_updated_at,
46
    before_updated_at,
47
    include_cleaned,
48
    include_transactional,
49
    include_unsubscribed,
50
  };
51
  for (const key in params) {
52
    const value = params[<keyof typeof params>key];
53
    if (value) {
54
      url.searchParams.append(
55
        key,
56
        Array.isArray(value) ? value.join(",") : "" + value,
57
      );
58
    }
59
  }
60

61
  const response = await fetch(url, {
62
    method: "GET",
63
    headers: {
64
      Authorization: `Bearer ${auth.api_key}`,
65
    },
66
  });
67

68
  if (!response.ok) {
69
    throw Error(await response.text());
70
  }
71
  return await response.json();
72
}
73