cal.pub0.org/pages/api/webhooks/_post.ts

60 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-10-19 18:26:12 +00:00
import type { Prisma } from "@prisma/client";
import type { NextApiRequest } from "next";
import { v4 as uuidv4 } from "uuid";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
2022-11-25 13:56:58 +00:00
import { schemaWebhookCreateBodyParams, schemaWebhookReadPublic } from "~/lib/validations/webhook";
2022-10-19 18:26:12 +00:00
/**
* @swagger
* /hooks:
* post:
* summary: Creates a new webhook
* operationId: addWebhook
* tags:
* - webhooks
* externalDocs:
* url: https://docs.cal.com/webhooks
* responses:
* 201:
* description: OK, webhook created
* 400:
* description: Bad request. webhook body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function postHandler(req: NextApiRequest) {
const { userId, isAdmin, prisma } = req;
const { eventTypeId, userId: bodyUserId, ...body } = schemaWebhookCreateBodyParams.parse(req.body);
const args: Prisma.WebhookCreateArgs = { data: { id: uuidv4(), ...body } };
// If no event type, we assume is for the current user. If admin we run more checks below...
if (!eventTypeId) args.data.userId = userId;
if (eventTypeId) {
const where: Prisma.EventTypeWhereInput = { id: eventTypeId };
if (!isAdmin) where.userId = userId;
await prisma.eventType.findFirstOrThrow({ where });
args.data.eventTypeId = eventTypeId;
}
if (!isAdmin && bodyUserId) throw new HttpError({ statusCode: 403, message: `ADMIN required for userId` });
if (isAdmin && bodyUserId) {
2022-10-21 18:55:15 +00:00
const where: Prisma.UserWhereInput = { id: bodyUserId };
2022-10-19 18:26:12 +00:00
await prisma.user.findFirstOrThrow({ where });
2022-10-21 18:55:15 +00:00
args.data.userId = bodyUserId;
2022-10-19 18:26:12 +00:00
}
const data = await prisma.webhook.create(args);
return {
webhook: schemaWebhookReadPublic.parse(data),
message: "Webhook created successfully",
};
}
export default defaultResponder(postHandler);