forked from tinacms/tina.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailchimp_helper.ts
49 lines (44 loc) · 1.17 KB
/
mailchimp_helper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { validate } from 'email-validator'
interface SubscriptionResult {
result: 'success' | 'error'
message: string
}
export async function addToMailchimp(
email: string,
firstName?: string,
lastName?: string
): Promise<SubscriptionResult> {
if (!validate(email)) {
return {
result: 'error',
message: 'The email you entered is not valid.',
}
}
const mergeFields: { FNAME?: string; LNAME?: string } = {};
if (firstName) mergeFields.FNAME = firstName;
if (lastName) mergeFields.LNAME = lastName;
try {
const response = await fetch('/api/mailchimp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email_address: email,
status: 'subscribed',
merge_fields: mergeFields,
}),
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.message || 'Failed to add email to the list.')
}
return {
result: 'success',
message: 'Email successfully added to the list.',
}
} catch (error) {
return {
result: 'error',
message: error.message || 'Failed to add email to the list.',
}
}
}