diff options
| author | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2024-04-07 09:59:17 +0100 |
|---|---|---|
| committer | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2024-04-07 09:59:17 +0100 |
| commit | 730c589a34e181b22bf720ca67f002baa0910b17 (patch) | |
| tree | da01a35f246d3010aa6a34f82f522b26fb01c74e /api/contact-form.ts | |
| parent | 7c923ef405a9128b8a0367094fce99833ec99c54 (diff) | |
git add api! WIP git add api! contact-form api endpointcontact-form
Diffstat (limited to 'api/contact-form.ts')
| -rw-r--r-- | api/contact-form.ts | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/api/contact-form.ts b/api/contact-form.ts new file mode 100644 index 0000000..a171020 --- /dev/null +++ b/api/contact-form.ts @@ -0,0 +1,50 @@ +import type { VercelRequest, VercelResponse } from '@vercel/node'; +import ContactFormSubmission from '_ContactFormSubmission'; +import CONTACT_DETAILS from '_contactDetails'; +import { sendEmail } from '_send-email'; + +export default async function handler(request: VercelRequest, response: VercelResponse) { + if (request.method !== 'POST') { + response.status(405).send('To send an enquiry, use the POST method.'); + return; + } + + const { recipient, name, email, subject, message }: Partial<ContactFormSubmission> = request.body; + + if (!recipient || recipient === '') { + response.status(400).send('Expected body to identify the recipient, but none was provided.'); + } else if (!name || name === '') { + response.status(400).send('Expected body to contain the name of the sender, but none was provided.'); + } else if (!email || email === '') { + response.status(400).send('Expected body to contain the email of the sender, but none was provided.'); + } else if (!subject || subject === '') { + response.status(400).send('Expected body to contain the subject of the enquiry, but none was provided.'); + } else if (!message || message === '') { + response.status(400).send('Expected body to contain the message body, but none was provided.'); + } + + const validRecipients = Object.keys(CONTACT_DETAILS); + if (!validRecipients.includes(recipient)) { + response.status(400).send( + 'Invalid recipient. Recipient must be one of: ' + + validRecipients.join(', ') + + '.' + ); + } + + try { + sendEmail({ + recipient, + senderName: name, + senderEmail: email, + subject, + body: message, + }); + } catch (err) { + response.status(500).send('Failed to send email: ' + err.toString()); + return; + } + + response.status(201).send(`Sent email to ${CONTACT_DETAILS[recipient].displayName}.`) +} + |
