2022-05-03 23:16:59 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
import { v4 } from "uuid";
|
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
import { scheduleTrigger } from "@calcom/app-store/zapier/lib/nodeScheduler";
|
2022-07-28 19:58:26 +00:00
|
|
|
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
2022-08-15 20:18:41 +00:00
|
|
|
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
2022-05-03 23:16:59 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2023-05-02 11:44:05 +00:00
|
|
|
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
2022-05-03 23:16:59 +00:00
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2022-05-03 23:16:59 +00:00
|
|
|
const apiKey = req.query.apiKey as string;
|
|
|
|
|
|
|
|
if (!apiKey) {
|
|
|
|
return res.status(401).json({ message: "No API key provided" });
|
|
|
|
}
|
|
|
|
|
|
|
|
const validKey = await findValidApiKey(apiKey, "zapier");
|
|
|
|
|
|
|
|
if (!validKey) {
|
|
|
|
return res.status(401).json({ message: "API key not valid" });
|
|
|
|
}
|
|
|
|
|
|
|
|
const { subscriberUrl, triggerEvent } = req.body;
|
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
try {
|
|
|
|
const createSubscription = await prisma.webhook.create({
|
|
|
|
data: {
|
|
|
|
id: v4(),
|
|
|
|
userId: validKey.userId,
|
|
|
|
eventTriggers: [triggerEvent],
|
|
|
|
subscriberUrl,
|
|
|
|
active: true,
|
|
|
|
appId: "zapier",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (triggerEvent === WebhookTriggerEvents.MEETING_ENDED) {
|
|
|
|
//schedule job for already existing bookings
|
|
|
|
const bookings = await prisma.booking.findMany({
|
|
|
|
where: {
|
2022-05-03 23:16:59 +00:00
|
|
|
userId: validKey.userId,
|
2022-08-15 20:18:41 +00:00
|
|
|
startTime: {
|
|
|
|
gte: new Date(),
|
|
|
|
},
|
|
|
|
status: BookingStatus.ACCEPTED,
|
2022-05-03 23:16:59 +00:00
|
|
|
},
|
|
|
|
});
|
2022-08-15 20:18:41 +00:00
|
|
|
|
|
|
|
for (const booking of bookings) {
|
|
|
|
scheduleTrigger(booking, createSubscription.subscriberUrl, {
|
|
|
|
id: createSubscription.id,
|
|
|
|
appId: createSubscription.appId,
|
|
|
|
});
|
|
|
|
}
|
2022-05-03 23:16:59 +00:00
|
|
|
}
|
2022-08-15 20:18:41 +00:00
|
|
|
res.status(200).json(createSubscription);
|
|
|
|
} catch (error) {
|
|
|
|
return res.status(500).json({ message: "Could not create subscription." });
|
2022-05-03 23:16:59 +00:00
|
|
|
}
|
|
|
|
}
|
2022-08-15 20:18:41 +00:00
|
|
|
|
|
|
|
export default defaultHandler({
|
|
|
|
POST: Promise.resolve({ default: defaultResponder(handler) }),
|
|
|
|
});
|