Add ses hook parser to capture all the events

This commit is contained in:
KMKoushik
2024-04-16 14:04:30 +10:00
parent 293277ed32
commit 9465960f0a
22 changed files with 712 additions and 105 deletions

View File

@@ -1,6 +1,7 @@
import { headers } from "next/headers";
import { hashToken } from "~/server/auth";
import { db } from "~/server/db";
import { parseSesHook } from "~/server/service/ses-hook-parser";
export async function GET(req: Request) {
console.log("GET", req);
@@ -10,67 +11,26 @@ export async function GET(req: Request) {
export async function POST(req: Request) {
const data = await req.json();
console.log(data, data.Message);
if (data.Type === "SubscriptionConfirmation") {
return handleSubscription(data);
}
console.log(data, data.Message);
let message = null;
try {
message = JSON.parse(data.Message || "{}");
const status = await parseSesHook(message);
if (!status) {
return Response.json({ data: "Error is parsing hook" }, { status: 400 });
}
return Response.json({ data: "Success" });
} catch (e) {
console.log(e);
console.error(e);
return Response.json({ data: "Error is parsing hook" }, { status: 400 });
}
const emailId = message?.mail.messageId;
console.log(emailId, message);
if (!emailId) {
return Response.json({ data: "Email not found" });
}
const email = await db.email.findUnique({
where: {
id: emailId,
},
});
if (!email || !message.mail) {
return Response.json({ data: "Email not found" });
}
console.log("FOund email", email);
await db.email.update({
where: {
id: email.id,
},
data: {
latestStatus: message.eventType,
},
});
await db.emailEvent.upsert({
where: {
emailId_status: {
emailId,
status: message.eventType,
},
},
update: {
data: message[message.eventType.toLowerCase()],
},
create: {
emailId,
status: message.eventType,
data: message[message.eventType.toLowerCase()],
},
});
return Response.json({ data: "Hello" });
}
async function handleSubscription(message: any) {
@@ -78,5 +38,5 @@ async function handleSubscription(message: any) {
method: "GET",
});
return Response.json({ data: "Hello" });
return Response.json({ data: "Success" });
}