1 | type Convertkit = { |
2 | apiSecret: string |
3 | } |
4 |
|
5 | const fetchSubscriberByEmail = async (resource: Convertkit, email: string) => { |
6 | const queryParams = new URLSearchParams({ |
7 | api_secret: resource.apiSecret, |
8 | email_address: email |
9 | }) |
10 |
|
11 | const endpoint = `https://api.convertkit.com/v3/subscribers?${queryParams.toString()}` |
12 |
|
13 | const response = await fetch(endpoint, { |
14 | method: 'GET', |
15 | headers: { |
16 | 'Content-Type': 'application/json' |
17 | } |
18 | }) |
19 |
|
20 | if (!response.ok) { |
21 | throw new Error( |
22 | `Failed to fetch subscriber that matches the provided email. Response code: ${response.status}` |
23 | ) |
24 | } |
25 |
|
26 | const data = await response.json() |
27 |
|
28 | if (data.subscribers && data.subscribers.length > 0) { |
29 | return data.subscribers[0] |
30 | } |
31 |
|
32 | throw new Error(`No subscriber found with the provided email`) |
33 | } |
34 |
|
35 | const fetchSubscribedTags = async (resource: Convertkit, subscriberId: string) => { |
36 | const queryParams = new URLSearchParams({ |
37 | api_secret: resource.apiSecret |
38 | }) |
39 |
|
40 | const endpoint = `https://api.convertkit.com/v3/subscribers/${subscriberId}/tags?${queryParams.toString()}` |
41 |
|
42 | const response = await fetch(endpoint, { |
43 | method: 'GET', |
44 | headers: { |
45 | 'Content-Type': 'application/json' |
46 | } |
47 | }) |
48 |
|
49 | if (!response.ok) { |
50 | throw new Error(`Failed to fetch tags. Response code: ${response.status}`) |
51 | } |
52 |
|
53 | const data = await response.json() |
54 |
|
55 | if (data.tags) { |
56 | return data.tags |
57 | } |
58 |
|
59 | throw new Error(`No tags found for the subscriber`) |
60 | } |
61 |
|
62 | export async function main(resource: Convertkit, email: string) { |
63 | const subscriber = await fetchSubscriberByEmail(resource, email) |
64 | const tags = await fetchSubscribedTags(resource, subscriber.id) |
65 |
|
66 | return tags |
67 | } |
68 |
|