-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforms.js
More file actions
57 lines (51 loc) · 1.57 KB
/
forms.js
File metadata and controls
57 lines (51 loc) · 1.57 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
export default {
async fetch(req, env) {
if (req.method === "OPTIONS")
return new Response(null, { headers: cors() });
if (req.method !== "POST")
return new Response("Internal Server Error", { status: 500, headers: cors() });
const ct = req.headers.get("content-type") || "";
let data = {};
if (ct.includes("application/json")) {
data = await req.json();
} else {
const form = await req.formData();
for (const [k, v] of form.entries()) {
if (k in data) {
data[k] += `,${v}`;
} else {
data[k] = v;
}
}
}
if (env.GAS_SHARED_SECRET) data.secret = env.GAS_SHARED_SECRET;
const controller = new AbortController();
const to = setTimeout(() => controller.abort("timeout"), 8000);
try {
const res = await fetch(env.GAS_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
signal: controller.signal,
});
const text = await res.text();
clearTimeout(to);
return new Response(text, {
status: res.status,
headers: { ...cors(), "Content-Type": "application/json" },
});
} catch (err) {
return new Response(JSON.stringify({ ok: false, error: String(err) }), {
status: 502,
headers: { ...cors(), "Content-Type": "application/json" },
});
}
},
};
function cors() {
return {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
}