-
-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathactions.ts
More file actions
63 lines (52 loc) · 1.49 KB
/
actions.ts
File metadata and controls
63 lines (52 loc) · 1.49 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use server";
import { z } from "zod";
const FormDataSchema = z.object({
email: z
.string({ error: "Email is required" })
.email({ error: "Must be a valid email address" }),
});
//@TODO - Add sentry to eat errors
const errorResponse = { message: "error" };
export async function subscribeToNewsletter(
prevState: { message: string },
formData: FormData,
): Promise<{ message: string }> {
try {
const result = FormDataSchema.parse({
email: formData.get("email"),
});
const { email } = result;
const EMAIL_API_ENDPOINT = process.env.EMAIL_API_ENDPOINT;
const EMAIL_API_KEY = process.env.EMAIL_API_KEY;
const EMAIL_NEWSLETTER_ID = process.env.EMAIL_NEWSLETTER_ID;
if (!EMAIL_API_ENDPOINT || !EMAIL_API_KEY || !EMAIL_NEWSLETTER_ID) {
console.log("Email API not configured");
return errorResponse;
}
const payload = new URLSearchParams({
email,
api_key: EMAIL_API_KEY,
list: EMAIL_NEWSLETTER_ID,
boolean: "true",
}).toString();
const response = await fetch(`${EMAIL_API_ENDPOINT}/subscribe`, {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
body: payload,
});
if (response.ok) {
// Send confirmation email to user
return {
message: "success",
};
} else {
console.log("Error:", response.status);
return errorResponse;
}
} catch (error) {
console.log(error);
return errorResponse;
}
}