This repository has been archived on 2025-06-12. You can view files and clone it, but cannot push or open issues or pull requests.
forms/server/src/handlers/submit/contactHandler.ts
2025-02-17 02:47:28 -08:00

64 lines
2.1 KiB
TypeScript

/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { validateBody } from "../../modules/validateBody.js";
import { logger } from "../../utils/logger.js";
import { sendMail } from "../../utils/mailer.js";
import type { PrismaClient } from "@prisma/client";
import type { Contact, ErrorResponse, SuccessResponse } from "@repo/types";
import type { FastifyReply, FastifyRequest } from "fastify";
/**
*Handles contact form submissions.
* @param database - The Prisma database client.
* @param request - The request object.
* @param response - The Fastify reply utility.
*/
export const submitContactHandler = async(
database: PrismaClient,
request: FastifyRequest<{ Body: Contact }>,
response: FastifyReply<{ Reply: SuccessResponse | ErrorResponse }>,
): Promise<void> => {
try {
const isInvalid = validateBody(
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We're passing a narrower type and TS hates that?
request.body as unknown as Record<string, unknown>,
"contacts",
);
if (isInvalid !== null) {
await response.status(400).send({ error: isInvalid });
return;
}
const exists = await database.contacts.findUnique({
where: {
email: request.body.email,
},
});
if (exists !== null) {
await response.
status(429).
send({
error:
// eslint-disable-next-line stylistic/max-len -- This is a long string.
"You have already submitted a contact request. Please wait for it to be reviewed.",
});
return;
}
const data = { ...request.body };
// @ts-expect-error -- We're deleting a property here.
delete data.consent;
await database.contacts.create({
data,
});
await sendMail("contact", data);
await response.send({ success: true });
} catch (error) {
await logger.error("/submit/contacts", error as Error);
await response.status(500).send({ error: error instanceof Error
? error.message
: "Internal Server Error" });
}
};