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

83 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-10-13 20:54:38 +00:00
import type { Prisma } from "@prisma/client";
import type { NextApiRequest } from "next";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
2022-10-13 20:54:38 +00:00
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
2022-11-25 13:56:58 +00:00
import { schemaCreateScheduleBodyParams, schemaSchedulePublic } from "~/lib/validations/schedule";
/**
* @swagger
* /schedules:
* post:
* operationId: addSchedule
* summary: Creates a new schedule
* parameters:
* - in: query
* name: apiKey
* schema:
* type: string
* required: true
* description: Your API Key
* requestBody:
* description: Create a new schedule
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* - timezone
* properties:
* name:
* type: string
* description: Name of the schedule
* timezone:
* type: string
* description: The timezone for this schedule
* tags:
* - schedules
* responses:
* 201:
* description: OK, schedule created
* 400:
* description: Bad request. Schedule body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
2022-10-13 20:54:38 +00:00
async function postHandler(req: NextApiRequest) {
const { userId, isAdmin, prisma } = req;
const body = schemaCreateScheduleBodyParams.parse(req.body);
let args: Prisma.ScheduleCreateArgs = { data: { ...body, userId } };
/* If ADMIN we create the schedule for selected user */
if (isAdmin && body.userId) args = { data: { ...body, userId: body.userId } };
if (!isAdmin && body.userId)
throw new HttpError({ statusCode: 403, message: "ADMIN required for `userId`" });
// We create default availabilities for the schedule
args.data.availability = {
createMany: {
data: getAvailabilityFromSchedule(DEFAULT_SCHEDULE).map((schedule) => ({
days: schedule.days,
startTime: schedule.startTime,
endTime: schedule.endTime,
})),
},
2022-10-13 20:54:38 +00:00
};
// We include the recently created availability
args.include = { availability: true };
2022-10-13 20:54:38 +00:00
const data = await prisma.schedule.create(args);
return {
2022-10-13 20:54:38 +00:00
schedule: schemaSchedulePublic.parse(data),
message: "Schedule created successfully",
};
}
export default defaultResponder(postHandler);