This repository has been archived by the owner on Oct 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
105 lines (100 loc) · 3.07 KB
/
worker.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
addEventListener("fetch", (event) => {
const { request } = event;
const { url } = request;
if (request.method === "POST") {
return event.respondWith(handlePostRequest(request));
} else if (request.method === "GET") {
return event.respondWith(handleGetRequest(request));
} else if (request.method === "OPTIONS") {
return event.respondWith(handleOptionsRequest(request));
}
});
async function handleGetRequest(request) {
return new Response("Object Not Found", {
statusText: "Object Not Found",
status: 404,
});
}
async function handleOptionsRequest(request) {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
}
})
}
async function handlePostRequest(request) {
let reqBody = await readRequestBody(request);
reqBody = JSON.parse(reqBody);
let emailResponse = await addContact({
email: reqBody.email,
type: reqBody.type,
});
return new Response(null, {
statusText: "OK",
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
}
});
}
async function readRequestBody(request) {
const { headers } = request;
const contentType = headers.get("content-type");
if (contentType.includes("application/json")) {
const body = JSON.stringify(await request.json());
return body;
} else if (contentType.includes("form")) {
const formData = await request.formData();
let body = {};
for (let entry of formData.entries()) {
body[entry[0]] = entry[1];
}
return JSON.stringify(body);
} else {
let myBlob = await request.blob();
var objectURL = URL.createObjectURL(myBlob);
return objectURL;
}
}
async function addContact({email, type}) {
console.log("reqBody", email, type);
let contact;
if (type) {
contact = await fetch(
"https://connect.mailerlite.com/api/subscribers",
{
body: JSON.stringify({
email: email,
groups: ["69914996139624088"],
}),
headers: {
Authorization: `Bearer ${MAILERLITE_API_KEY}`,
"Content-Type": "application/json",
"Accept": "application/json",
},
method: "POST",
}
);
}
else {
contact = await fetch(
"https://connect.mailerlite.com/api/subscribers",
{
body: JSON.stringify({
email: email,
groups: ["69914991802713582"],
}),
headers: {
Authorization: `Bearer ${MAILERLITE_API_KEY}`,
"Content-Type": "application/json",
"Accept": "application/json",
},
method: "POST",
}
);
};
console.log(await contact.json());
return contact;
}