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

57 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-07-31 17:22:48 +00:00
import type { BlitzApiRequest, BlitzApiResponse } from "blitz";
import zod from "zod";
2021-07-31 14:33:18 +00:00
2021-08-12 13:52:52 +00:00
import type { ApiError } from "../../_types";
import appLogger from "integrations/logger";
import { addSubscriber } from "integrations/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
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") {
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
}