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
/**
* This Val creates a simple API endpoint that saves an email address for notifications
* using Val Town's JSON storage. It handles POST requests to save the submitted email
* and returns a simple confirmation message.
*/
async function server(request: Request): Promise<Response> {
const { blob } = await import("https://esm.town/v/std/blob");
const KEY = new URL(import.meta.url).pathname.split("/").at(-1);
console.log(await blob.getJSON(`${KEY}_subscribers`));
if (request.method === "POST") {
const formData = await request.formData();
const email = formData.get("email");
if (email) {
try {
// Get existing subscribers or initialize an empty array
const subscribers = await blob.getJSON(`${KEY}_subscribers`) || [];
// Check if email already exists
if (subscribers.includes(email)) {
return new Response("this email is already subscribed (◕‿◕)");
}
// Add new email and save
subscribers.push(email);
await blob.setJSON(`${KEY}_subscribers`, subscribers);
return new Response("you've signed up \(≧▽≦)/");
} catch (error) {
console.error("Error saving email:", error);
return new Response("an error occurred. please try again. (。•́︿•̀。)");
}
} else {
return new Response("please provide an email address (◕‿◕) ");
}
}
// For any other request method, return a simple message
return new Response("Send a POST request with an 'email' field to sign up (◕‿◕)");
}
export default server;