-
Notifications
You must be signed in to change notification settings - Fork 1
/
submitForm.ts
55 lines (45 loc) · 1.11 KB
/
submitForm.ts
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
export interface FormDataType {
[key: string]: string | string[];
}
export async function submitForm(id: string, data: FormDataType) {
const url = `https://docs.google.com/forms/d/e/${id}/formResponse`;
const formData = new FormData();
const email = data['emailAddress'];
if (email) {
if (Array.isArray(email)) {
return {
error: true,
message: 'Email address cannot be an array'
}
} else {
formData.append('emailAddress', email);
}
}
delete data['emailAddress'];
// Handle other fields
Object.entries(data).forEach(([key, value]) => {
const id = `entry.${key}`;
if (Array.isArray(value)) {
value.forEach((v) => {
formData.append(id, v);
});
return;
} else {
formData.append(id, value);
}
});
const response = await fetch(url, {
method: 'POST',
body: formData
});
if (!response.ok) {
return {
error: true,
message: 'Unable to submit the form. Check your form ID and email settings, and try again.'
}
}
return {
error: false,
message: 'Form submitted successfully'
}
}