Skip to content

Commit

Permalink
144 process-email type validation with zod (#157)
Browse files Browse the repository at this point in the history
* adding type validation with Zod for process-email

* Feature: Type validation with zod for process-email api
  • Loading branch information
Sadaf-A committed Sep 14, 2023
1 parent f11cb83 commit 641fcf1
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/pages/api/process-email.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import type { NextApiRequest, NextApiResponse } from "next";
import sgMail from "@sendgrid/mail";
import { z } from "zod";

// Define The Zod schema for the request body
const Email = z.object({
name: z.string(),
email: z.string().email(),
message: z.string(),
});

interface ExtendedNextApiRequest extends NextApiRequest {
body: Email
body: z.infer<typeof Email>;
}

export default async function handleSubscribe(
Expand All @@ -15,6 +23,14 @@ export default async function handleSubscribe(
const badRequest = req.method !== "POST" || requestEmpty;
if( badRequest ) return res.status(400).json({ data: "Please send a properly formatted request" });

// Validate the request body against the Zod schema
try {
Email.parse(req.body);
} catch (error) {
console.error("Request body validation failed:", error);
return res.status(400).json({ data: "Invalid request body" });
}

sgMail.setApiKey(process.env.NEXT_PUBLIC_SENDGRID_API_KEY as string);

const msg = {
Expand Down

0 comments on commit 641fcf1

Please sign in to comment.