1 | |
2 |
|
3 | |
4 | * @param fields *(optional)* A list of fields to return in the response. |
5 | * Reference parameters of sub-objects with dot notation. |
6 | * |
7 | * @param exclude_fields *(optional)* A list of fields to exclude from the response. |
8 | * Reference parameters of sub-objects with dot notation. If both `fields` and `exclude_fields` |
9 | * are present, then only `exclude_fields` will be used. |
10 | */ |
11 | type Mailchimp = { |
12 | api_key: string; |
13 | server: string; |
14 | }; |
15 | export async function main( |
16 | auth: Mailchimp, |
17 | list_id: string, |
18 | segment_id: string, |
19 | fields?: string[], |
20 | exclude_fields?: string[], |
21 | include_cleaned?: boolean, |
22 | include_transactional?: boolean, |
23 | include_unsubscribed?: boolean, |
24 | ) { |
25 | const url = new URL( |
26 | `https://${auth.server}.api.mailchimp.com/3.0/lists/${list_id}/segments/${segment_id}`, |
27 | ); |
28 | const params = { |
29 | fields, |
30 | exclude_fields, |
31 | include_cleaned, |
32 | include_transactional, |
33 | include_unsubscribed, |
34 | }; |
35 | for (const key in params) { |
36 | const value = params[<keyof typeof params>key]; |
37 | if (value) { |
38 | url.searchParams.append( |
39 | key, |
40 | Array.isArray(value) ? value.join(",") : "" + value, |
41 | ); |
42 | } |
43 | } |
44 |
|
45 | const response = await fetch(url, { |
46 | method: "GET", |
47 | headers: { |
48 | Authorization: `Bearer ${auth.api_key}`, |
49 | }, |
50 | }); |
51 |
|
52 | if (!response.ok) { |
53 | throw Error(await response.text()); |
54 | } |
55 | return await response.json(); |
56 | } |
57 |
|