2023-08-20 17:20:24 -06:00
|
|
|
import { type NextRequest, NextResponse } from "next/server";
|
2023-08-14 21:16:11 -06:00
|
|
|
import {
|
|
|
|
onUserCreatedHandler,
|
|
|
|
onUserDeletedHandler,
|
|
|
|
} from "~/server/webhookHelpers";
|
2023-08-22 21:26:26 -06:00
|
|
|
import {
|
|
|
|
WebhookEventBody,
|
|
|
|
WebhookEventBodySchema,
|
|
|
|
WebhookEvents,
|
|
|
|
} from "~/utils/types";
|
2023-08-14 21:16:11 -06:00
|
|
|
|
2023-08-20 17:20:24 -06:00
|
|
|
export const config = {
|
|
|
|
runtime: "edge",
|
|
|
|
regions: ["pdx1"],
|
|
|
|
};
|
|
|
|
|
|
|
|
export default async function handler(req: NextRequest) {
|
2023-08-15 00:54:46 -06:00
|
|
|
try {
|
2023-08-22 21:26:26 -06:00
|
|
|
const eventBody = (await req.json()) as WebhookEventBody;
|
2023-08-22 21:52:38 -06:00
|
|
|
console.log(eventBody);
|
2023-08-22 21:26:26 -06:00
|
|
|
const { data, type } = WebhookEventBodySchema.parse(eventBody);
|
2023-08-20 17:20:24 -06:00
|
|
|
let success = false;
|
2023-08-14 21:16:11 -06:00
|
|
|
|
2023-08-22 21:26:26 -06:00
|
|
|
switch (type) {
|
2023-08-15 00:54:46 -06:00
|
|
|
case WebhookEvents.USER_CREATED:
|
2023-08-22 21:26:26 -06:00
|
|
|
success = await onUserCreatedHandler(
|
|
|
|
data.id,
|
|
|
|
`${data.first_name} ${data.last_name}`,
|
|
|
|
data.email_addresses?.map((email) => email.email_address) || []
|
|
|
|
);
|
2023-08-20 17:20:24 -06:00
|
|
|
if (success) {
|
|
|
|
return NextResponse.json(
|
|
|
|
{ result: "USER CREATED" },
|
|
|
|
{ status: 200, statusText: "USER CREATED" }
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
return NextResponse.json(
|
|
|
|
{ result: "USER WITH THIS ID NOT FOUND" },
|
|
|
|
{ status: 404, statusText: "USER WITH THIS ID NOT FOUND" }
|
|
|
|
);
|
|
|
|
}
|
2023-08-14 21:16:11 -06:00
|
|
|
|
2023-08-15 00:54:46 -06:00
|
|
|
case WebhookEvents.USER_DELETED:
|
2023-08-22 21:26:26 -06:00
|
|
|
success = await onUserDeletedHandler(data.id);
|
2023-08-20 17:20:24 -06:00
|
|
|
|
|
|
|
return NextResponse.json(
|
|
|
|
{ result: "USER DELETED" },
|
|
|
|
{ status: 200, statusText: "USER DELETED" }
|
|
|
|
);
|
2023-08-14 21:16:11 -06:00
|
|
|
|
2023-08-15 00:54:46 -06:00
|
|
|
default:
|
2023-08-20 17:20:24 -06:00
|
|
|
return NextResponse.json(
|
|
|
|
{ result: "INVALID WEBHOOK EVENT TYPE" },
|
|
|
|
{ status: 400, statusText: "INVALID WEBHOOK EVENT TYPE" }
|
|
|
|
);
|
2023-08-15 00:54:46 -06:00
|
|
|
}
|
2023-08-22 21:26:26 -06:00
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
2023-08-20 17:20:24 -06:00
|
|
|
return NextResponse.json(
|
|
|
|
{ result: "INVALID WEBHOOK EVENT BODY" },
|
|
|
|
{ status: 400, statusText: "INVALID WEBHOOK EVENT BODY" }
|
|
|
|
);
|
2023-08-14 21:16:11 -06:00
|
|
|
}
|
|
|
|
}
|