pollo/src/pages/api/webhooks/index.ts

54 lines
1.5 KiB
TypeScript
Raw Normal View History

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-15 00:54:46 -06:00
import { 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-20 17:20:24 -06:00
const requestBody = WebhookEventBodySchema.parse(await req.json());
let success = false;
2023-08-14 21:16:11 -06:00
2023-08-15 00:54:46 -06:00
switch (requestBody.type) {
case WebhookEvents.USER_CREATED:
2023-08-20 17:20:24 -06:00
success = await onUserCreatedHandler(requestBody.data.id);
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-20 17:20:24 -06:00
success = await onUserDeletedHandler(requestBody.data.id);
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
}
} catch {
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
}
}