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
|
import 'dotenv/config';
import sgMail from '@sendgrid/mail';
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
export async function get() {
const items = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
];
return {
body: items
};
}
export async function post({ request }) {
const body = await request.json();
const { HCAPTCHA_SECRET, FORM_FROM_EMAIL, FORM_TO_EMAIL } = process.env;
const captchaVerified = await fetch(`https://hcaptcha.com/siteverify?response=${body.captchaToken}&secret=${HCAPTCHA_SECRET}`, {
method: 'POST',
})
.then((res) => res.json())
.then((json) => json.success)
.catch(() => false);
if (!captchaVerified) {
return {
statusCode: 400,
body: {
error: 'Captcha verification failed',
},
};
}
const msg = {
to: FORM_TO_EMAIL,
from: FORM_FROM_EMAIL,
subject: `Form Submission from ${body.name}`,
text: `
Name: ${body.name}
Email: ${body.email}
Message: ${body.message}
`,
};
const messageSent = await sgMail
.send(msg)
.then(() => true)
.catch((error) => {
console.error(error);
return false;
});
if (!messageSent) {
return {
statusCode: 500,
body: {
error: 'Message could not be sent',
},
};
}
return {
body: {
success: true,
},
};
}
|