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
import { blob } from "https://esm.town/v/std/blob?v=11";
import { email } from "https://esm.town/v/std/email?v=11";
import { thisWebURL } from "https://esm.town/v/stevekrouse/thisWebURL?v=2";
export const renderFormAndSaveData = async (req: Request) => {
// A visit from a web browser? Serve a HTML page with a form
if (req.method === "GET") {
return new Response(
`
<!DOCTYPE html>
<html>
<head>
<title>Email Form</title>
</head>
<body>
<form action="${thisWebURL()}" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`,
{ headers: { "Content-Type": "text/html" } },
);
}
// Get existing list of submitted email addresses
let submittedEmailAddresses = await blob.getJSON("submittedEmailAddresses") as string[];
// If there were no email addresses stored, create an empty array
submittedEmailAddresses ??= [];
// Pick out the form data
const formData = await req.formData();
const emailAddress = formData.get("email") as string;
if (submittedEmailAddresses.includes(emailAddress)) {
return new Response("You're already signed up!");
}
email({ text: `${emailAddress} just signed up!`, subject: "New sign up" });
// Store form data
submittedEmailAddresses.push(emailAddress);
await blob.setJSON("submittedEmailAddresses", submittedEmailAddresses);
return new Response("Thanks! You're signed up!");
};