0
Get Segment
One script reply has been approved by the moderators Verified

Get information about a specific segment.

Created by adam186 508 days ago Viewed 4333 times
0
Submitted by adam186 Deno
Verified 507 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
type Mailchimp = {
10
  api_key: string;
11
  server: string;
12
};
13
export async function main(
14
  auth: Mailchimp,
15
  list_id: string,
16
  segment_id: string,
17
  fields?: string[],
18
  exclude_fields?: string[],
19
  include_cleaned?: boolean,
20
  include_transactional?: boolean,
21
  include_unsubscribed?: boolean,
22
) {
23
  const url = new URL(
24
    `https://${auth.server}.api.mailchimp.com/3.0/lists/${list_id}/segments/${segment_id}`,
25
  );
26
  const params = {
27
    fields,
28
    exclude_fields,
29
    include_cleaned,
30
    include_transactional,
31
    include_unsubscribed,
32
  };
33
  for (const key in params) {
34
    const value = params[<keyof typeof params>key];
35
    if (value) {
36
      url.searchParams.append(
37
        key,
38
        Array.isArray(value) ? value.join(",") : "" + value,
39
      );
40
    }
41
  }
42

43
  const response = await fetch(url, {
44
    method: "GET",
45
    headers: {
46
      Authorization: `Bearer ${auth.api_key}`,
47
    },
48
  });
49

50
  if (!response.ok) {
51
    throw Error(await response.text());
52
  }
53
  return await response.json();
54
}
55