shellphone.app/app/api/newsletter/subscribe.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

import type { NextApiRequest, NextApiResponse } from "next";
import zod from "zod";
2021-07-31 14:33:18 +00:00
import type { ApiError } from "../_types";
import appLogger from "../../../integrations/logger";
import { addSubscriber } from "./_mailchimp";
2021-07-31 14:33:18 +00:00
type Response = {} | ApiError;
2021-07-31 14:33:18 +00:00
const logger = appLogger.child({ route: "/api/newsletter/subscribe" });
2021-07-31 14:33:18 +00:00
const bodySchema = zod.object({
email: zod.string().email(),
});
2021-07-31 14:33:18 +00:00
export default async function subscribeToNewsletter(
req: NextApiRequest,
res: NextApiResponse<Response>
) {
if (req.method !== "POST") {
const statusCode = 405;
2021-07-31 14:33:18 +00:00
const apiError: ApiError = {
statusCode,
errorMessage: `Method ${req.method} Not Allowed`,
};
logger.error(apiError);
2021-07-31 14:33:18 +00:00
res.setHeader("Allow", ["POST"]);
res.status(statusCode).send(apiError);
return;
2021-07-31 14:33:18 +00:00
}
let body;
2021-07-31 14:33:18 +00:00
try {
body = bodySchema.parse(req.body);
2021-07-31 14:33:18 +00:00
} catch (error) {
const statusCode = 400;
2021-07-31 14:33:18 +00:00
const apiError: ApiError = {
statusCode,
errorMessage: "Body is malformed",
};
logger.error(error);
2021-07-31 14:33:18 +00:00
res.status(statusCode).send(apiError);
return;
2021-07-31 14:33:18 +00:00
}
try {
await addSubscriber(body.email);
2021-07-31 14:33:18 +00:00
} catch (error) {
console.log("error", error.response?.data);
2021-07-31 14:33:18 +00:00
if (error.response?.data.title !== "Member Exists") {
return res.status(error.response?.status ?? 400).end();
2021-07-31 14:33:18 +00:00
}
}
res.status(200).end();
2021-07-31 14:33:18 +00:00
}