2021-07-31 17:22:48 +00:00
|
|
|
import type { BlitzApiRequest, BlitzApiResponse } from "blitz";
|
2021-07-31 15:57:43 +00:00
|
|
|
import zod from "zod";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
import type { ApiError } from "../_types";
|
|
|
|
import appLogger from "../../../integrations/logger";
|
|
|
|
import { addSubscriber } from "./_mailchimp";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
type Response = {} | ApiError;
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +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 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 14:03:49 +00:00
|
|
|
export default async function subscribeToNewsletter(req: BlitzApiRequest, res: BlitzApiResponse<Response>) {
|
2021-07-31 14:33:18 +00:00
|
|
|
if (req.method !== "POST") {
|
2021-07-31 15:57:43 +00:00
|
|
|
const statusCode = 405;
|
2021-07-31 14:33:18 +00:00
|
|
|
const apiError: ApiError = {
|
|
|
|
statusCode,
|
|
|
|
errorMessage: `Method ${req.method} Not Allowed`,
|
2021-07-31 15:57:43 +00:00
|
|
|
};
|
|
|
|
logger.error(apiError);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
res.setHeader("Allow", ["POST"]);
|
|
|
|
res.status(statusCode).send(apiError);
|
|
|
|
return;
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
let body;
|
2021-07-31 14:33:18 +00:00
|
|
|
try {
|
2021-07-31 15:57:43 +00:00
|
|
|
body = bodySchema.parse(req.body);
|
2021-08-27 18:05:44 +00:00
|
|
|
} catch (error: any) {
|
2021-07-31 15:57:43 +00:00
|
|
|
const statusCode = 400;
|
2021-07-31 14:33:18 +00:00
|
|
|
const apiError: ApiError = {
|
|
|
|
statusCode,
|
|
|
|
errorMessage: "Body is malformed",
|
2021-07-31 15:57:43 +00:00
|
|
|
};
|
|
|
|
logger.error(error);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
res.status(statusCode).send(apiError);
|
|
|
|
return;
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2021-07-31 15:57:43 +00:00
|
|
|
await addSubscriber(body.email);
|
2021-08-27 18:05:44 +00:00
|
|
|
} catch (error: any) {
|
2021-07-31 15:57:43 +00:00
|
|
|
console.log("error", error.response?.data);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
if (error.response?.data.title !== "Member Exists") {
|
2021-07-31 15:57:43 +00:00
|
|
|
return res.status(error.response?.status ?? 400).end();
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
res.status(200).end();
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|