cal.pub0.org/pages/api/bookings/index.ts

153 lines
5.1 KiB
TypeScript
Raw Normal View History

import { WebhookTriggerEvents } from "@prisma/client";
2022-06-10 08:08:45 +00:00
import type { NextApiRequest, NextApiResponse } from "next";
2022-06-11 11:27:35 +00:00
import { v4 as uuidv4 } from "uuid";
2022-06-10 10:27:31 +00:00
import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
2022-06-10 08:08:45 +00:00
import { BookingResponse, BookingsResponse } from "@lib/types";
import sendPayload from "@lib/utils/sendPayload";
import getWebhooks from "@lib/utils/webhookSubscriptions";
import { schemaBookingCreateBodyParams, schemaBookingReadPublic } from "@lib/validations/booking";
import { schemaEventTypeReadPublic } from "@lib/validations/event-type";
2022-03-26 21:29:30 +00:00
async function createOrlistAllBookings(
2022-04-30 18:53:19 +00:00
{ method, body, userId }: NextApiRequest,
res: NextApiResponse<BookingsResponse | BookingResponse>
) {
console.log("userIduserId", userId);
if (method === "GET") {
2022-04-29 15:29:57 +00:00
/**
* @swagger
* /bookings:
* get:
* summary: Find all bookings
* operationId: listBookings
2022-04-29 15:29:57 +00:00
* tags:
* - bookings
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No bookings were found
*/
const data = await prisma.booking.findMany({ where: { userId } });
const bookings = data.map((booking) => schemaBookingReadPublic.parse(booking));
if (bookings) res.status(200).json({ bookings });
else
(error: Error) =>
res.status(404).json({
message: "No Bookings were found",
error,
});
} else if (method === "POST") {
2022-04-29 15:29:57 +00:00
/**
* @swagger
* /bookings:
* post:
* summary: Creates a new booking
* operationId: addBooking
* requestBody:
* description: Edit an existing booking related to one of your event-types
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* example: 15min
* startTime:
* type: string
* example: 1970-01-01T17:00:00.000Z
* endTime:
* type: string
* example: 1970-01-01T17:00:00.000Z
2022-04-29 15:29:57 +00:00
* tags:
* - bookings
* responses:
* 201:
* description: OK, booking created
* 400:
* description: Bad request. Booking body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
2022-04-30 18:53:19 +00:00
const safe = schemaBookingCreateBodyParams.safeParse(body);
if (!safe.success) {
console.log(safe.error);
res.status(400).json({ message: "Bad request. Booking body is invalid." });
return;
}
safe.data.userId = userId;
2022-06-11 11:28:21 +00:00
const data = await prisma.booking.create({ data: { uid: uuidv4(), ...safe.data } });
const booking = schemaBookingReadPublic.parse(data);
2022-06-09 11:39:20 +00:00
if (booking) {
res.status(201).json({ booking, message: "Booking created successfully" });
2022-06-10 10:51:55 +00:00
// Create Calendar Event for webhook payload
const eventType = await prisma.eventType
2022-06-10 07:23:59 +00:00
.findUnique({ where: { id: booking.eventTypeId as number } })
.then((data) => schemaEventTypeReadPublic.parse(data))
2022-06-11 11:33:11 +00:00
.catch((e: Error) => {
console.error(`Event type with ID: ${booking.eventTypeId} not found`, e);
});
const evt = {
2022-06-10 07:36:22 +00:00
type: eventType?.title || booking.title,
title: booking.title,
description: "",
additionalNotes: "",
customInputs: {},
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
organizer: {
name: "",
email: "",
2022-06-10 07:52:06 +00:00
timeZone: "",
language: {
2022-06-10 08:08:45 +00:00
locale: "en",
2022-06-10 10:51:55 +00:00
},
},
attendees: [],
location: "",
destinationCalendar: null,
hideCalendar: false,
uid: booking.uid,
2022-06-10 10:51:55 +00:00
metadata: {},
};
2022-06-10 10:51:55 +00:00
// Send Webhook call if hooked to BOOKING_CREATED
const triggerEvent = WebhookTriggerEvents.BOOKING_CREATED;
const subscriberOptions = {
userId,
2022-06-10 07:40:16 +00:00
eventTypeId: booking.eventTypeId as number,
triggerEvent,
};
2022-06-10 10:51:55 +00:00
const subscribers = await getWebhooks(subscriberOptions);
const bookingId = booking?.id;
const promises = subscribers.map((sub) =>
2022-06-10 07:21:24 +00:00
sendPayload(triggerEvent, new Date().toISOString(), sub, {
...evt,
bookingId,
}).catch((e) => {
2022-06-10 07:21:24 +00:00
console.error(`Error executing webhook for event: ${triggerEvent}, URL: ${sub.subscriberUrl}`, e);
})
);
await Promise.all(promises);
2022-06-10 11:06:28 +00:00
} else
(error: Error) => {
console.log(error);
res.status(400).json({
message: "Could not create new booking",
error,
});
};
} else res.status(405).json({ message: `Method ${method} not allowed` });
2022-03-26 21:29:30 +00:00
}
export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllBookings);