-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
105 lines (97 loc) · 2.61 KB
/
index.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
import validate from './validator'
import sendMail from './email-service'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Max-Age': '86400',
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === 'POST') {
return handlePostRequest(request)
} else if (request.method === 'OPTIONS') {
return new Response('OK', { headers: corsHeaders })
} else {
return new Response('Object Not Found', {
statusText: 'Object Not Found',
status: 404,
})
}
}
/**
* Return body data in JSON format
* @param {Request} request
*/
async function readRequestBody(request) {
const { headers } = request
const contentType = headers.get('content-type')
if (!contentType) {
throw 'Content type has not been set!'
}
if (contentType.includes('application/json')) {
const body = 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 {
throw 'Content type not recognized!'
}
}
/**
* Handle JSON POST request
* @param {Request} request
*/
async function handlePostRequest(request) {
let json
try {
json = await readRequestBody(request)
} catch (error) {
return new Response(error, {
headers: { 'content-type': 'text/plain', ...corsHeaders },
statusText: error,
status: 500,
})
}
// Validate json inputs
const results = validate(json)
// Return 400 Error Response for invalid post request
if (!results.valid) {
return new Response(JSON.stringify(results), {
headers: { 'content-type': 'text/json', ...corsHeaders },
status: 400,
})
}
try {
const result = await sendMail(json)
if (result.status == 200) {
return new Response(
JSON.stringify({ message: 'Message succesfully sent' }),
{
headers: { 'content-type': 'text/json', ...corsHeaders },
},
)
} else {
return new Response(
JSON.stringify({ message: 'Message submission failed!', result }),
{
headers: { 'content-type': 'text/json', ...corsHeaders },
status: 400,
},
)
}
} catch (error) {
return new Response(error, {
headers: { 'content-type': 'text/plain', ...corsHeaders },
statusText: 'An error occurred',
status: 500,
})
}
}