click to action on landing page

This commit is contained in:
m5r
2021-08-28 05:09:45 +08:00
parent e7c69a4d7a
commit 1e89e57145
9 changed files with 140 additions and 190 deletions

View File

@ -1,4 +0,0 @@
export type ApiError = {
statusCode: number;
errorMessage: string;
};

View File

@ -1,21 +0,0 @@
import { getConfig } from "blitz";
import got from "got";
const { serverRuntimeConfig } = getConfig();
export async function addSubscriber(email: string) {
const { apiKey, audienceId } = serverRuntimeConfig.mailChimp;
const region = apiKey.split("-")[1];
const url = `https://${region}.api.mailchimp.com/3.0/lists/${audienceId}/members`;
const data = {
email_address: email,
status: "subscribed",
};
const base64ApiKey = Buffer.from(`any:${apiKey}`).toString("base64");
const headers = {
"Content-Type": "application/json",
Authorization: `Basic ${base64ApiKey}`,
};
return got.post(url, { json: data, headers });
}

View File

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