Scheduling infrastructure for absolutely everyone.
Refactors event-types endpoints (#181)
Omar Lópezf13694fd1300
diff --git a/lib/validations/event-type.ts b/lib/validations/event-type.tsindex 16065e668c6..8cf3fece84e 100644--- a/lib/validations/event-type.ts+++ b/lib/validations/event-type.ts@@ -3,9 +3,19 @@ import { z } from "zod";import { _EventTypeModel as EventType } from "@calcom/prisma/zod";import { Frequency } from "@lib/types";-import { timeZone } from "@lib/validations/shared/timeZone";import { jsonSchema } from "./shared/jsonSchema";+import { schemaQueryUserId } from "./shared/queryUserId";+import { timeZone } from "./shared/timeZone";++const recurringEventInputSchema = z.object({+ dtstart: z.string().optional(),+ interval: z.number().int().optional(),+ count: z.number().int().optional(),+ freq: z.nativeEnum(Frequency).optional(),+ until: z.string().optional(),+ tzid: timeZone.optional(),+});export const schemaEventTypeBaseBodyParams = EventType.pick({title: true,@@ -13,7 +23,6 @@ export const schemaEventTypeBaseBodyParams = EventType.pick({length: true,hidden: true,position: true,- userId: true,teamId: true,eventName: true,timeZone: true,@@ -33,7 +42,10 @@ export const schemaEventTypeBaseBodyParams = EventType.pick({currency: true,slotInterval: true,successRedirectUrl: true,-}).partial();+ locations: true,+})+ .partial()+ .strict();const schemaEventTypeCreateParams = z.object({@@ -41,14 +53,14 @@ const schemaEventTypeCreateParams = zslug: z.string(),description: z.string().optional().nullable(),length: z.number().int(),- locations: jsonSchema.optional(),metadata: z.any().optional(),- recurringEvent: jsonSchema.optional(),+ recurringEvent: recurringEventInputSchema.optional(),}).strict();-export const schemaEventTypeCreateBodyParams =- schemaEventTypeBaseBodyParams.merge(schemaEventTypeCreateParams);+export const schemaEventTypeCreateBodyParams = schemaEventTypeBaseBodyParams+ .merge(schemaEventTypeCreateParams)+ .merge(schemaQueryUserId.partial());const schemaEventTypeEditParams = z.object({@@ -92,17 +104,6 @@ export const schemaEventTypeReadPublic = EventType.pick({metadata: true,}).merge(z.object({- recurringEvent: z- .object({- dtstart: z.date().optional(),- interval: z.number().int().optional(),- count: z.number().int().optional(),- freq: z.nativeEnum(Frequency).optional(),- until: z.date().optional(),- tzid: timeZone.optional(),- })- .optional()- .nullable(),locations: z.array(z.object({diff --git a/lib/validations/shared/queryUserId.ts b/lib/validations/shared/queryUserId.tsindex 94a7700003d..94de53a214e 100644--- a/lib/validations/shared/queryUserId.ts+++ b/lib/validations/shared/queryUserId.ts@@ -1,18 +1,22 @@import { withValidation } from "next-validations";import { z } from "zod";+import { stringOrNumber } from "@calcom/prisma/zod-utils";+import { baseApiParams } from "./baseApiParams";// Extracted out as utility function so can be reused// at different endpoints that require this validation.export const schemaQueryUserId = baseApiParams.extend({- userId: z- .string()- .regex(/^\d+$/)- .transform((id) => parseInt(id)),+ userId: stringOrNumber,}).strict();++export const schemaQuerySingleOrMultipleUserIds = z.object({+ userId: z.union([stringOrNumber, z.array(stringOrNumber)]),+});+export const withValidQueryUserId = withValidation({schema: schemaQueryUserId,type: "Zod",diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].tsdeleted file mode 100644index bd8c8234898..00000000000--- a/pages/api/event-types/[id].ts+++ /dev/null@@ -1,172 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import type { EventTypeResponse } from "@lib/types";-import { schemaEventTypeEditBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";-import {- schemaQueryIdParseInt,- withValidQueryIdTransformParseInt,-} from "@lib/validations/shared/queryIdTransformParseInt";--export async function eventTypeById(- { method, query, body, userId, isAdmin, prisma }: NextApiRequest,- res: NextApiResponse<EventTypeResponse>-) {- if (body.userId && !isAdmin) {- res.status(401).json({ message: "Unauthorized" });- return;- }- const safeQuery = schemaQueryIdParseInt.safeParse(query);- if (!safeQuery.success) {- res.status(400).json({ message: "Your query was invalid" });- return;- }- const data = await prisma.user.findUnique({- where: { id: body.userId || userId },- rejectOnNotFound: true,- select: { eventTypes: true },- });- const userEventTypes = data.eventTypes.map((eventType) => eventType.id);- if (!userEventTypes.includes(safeQuery.data.id)) {- res.status(401).json({ message: "Unauthorized" });- return;- } else {- switch (method) {- /**- * @swagger- * /event-types/{id}:- * get:- * operationId: getEventTypeById- * summary: Find a eventType- * parameters:- * - in: path- * name: id- * example: 4- * schema:- * type: integer- * required: true- * description: ID of the eventType to get- * security:- * - ApiKeyAuth: []- * tags:- * - event-types- * externalDocs:- * url: https://docs.cal.com/event-types- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: EventType was not found- */- case "GET":- await prisma.eventType- .findUnique({ where: { id: safeQuery.data.id } })- .then((data) => schemaEventTypeReadPublic.parse(data))- .then((event_type) => res.status(200).json({ event_type }))- .catch((error: Error) =>- res.status(404).json({- message: `EventType with id: ${safeQuery.data.id} not found`,- error,- })- );- break;- /**- * @swagger- * /event-types/{id}:- * patch:- * operationId: editEventTypeById- * summary: Edit an existing eventType- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: ID of the eventType to edit- * security:- * - ApiKeyAuth: []- * tags:- * - event-types- * externalDocs:- * url: https://docs.cal.com/event-types- * responses:- * 201:- * description: OK, eventType edited successfuly- * 400:- * description: Bad request. EventType body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */- case "PATCH":- const safeBody = schemaEventTypeEditBodyParams.safeParse(body);-- if (!safeBody.success) {- {- res.status(400).json({ message: "Invalid request body" });- return;- }- }- await prisma.eventType- .update({ where: { id: safeQuery.data.id }, data: safeBody.data })- .then((data) => schemaEventTypeReadPublic.parse(data))- .then((event_type) => res.status(200).json({ event_type }))- .catch((error: Error) =>- res.status(404).json({- message: `EventType with id: ${safeQuery.data.id} not found`,- error,- })- );- break;- /**- * @swagger- * /event-types/{id}:- * delete:- * operationId: removeEventTypeById- * summary: Remove an existing eventType- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: ID of the eventType to delete- * security:- * - ApiKeyAuth: []- * tags:- * - event-types- * externalDocs:- * url: https://docs.cal.com/event-types- * responses:- * 201:- * description: OK, eventType removed successfuly- * 400:- * description: Bad request. EventType id is invalid.- * 401:- * description: Authorization information is missing or invalid.- */- case "DELETE":- await prisma.eventType- .delete({ where: { id: safeQuery.data.id } })- .then(() =>- res.status(200).json({- message: `EventType with id: ${safeQuery.data.id} deleted`,- })- )- .catch((error: Error) =>- res.status(404).json({- message: `EventType with id: ${safeQuery.data.id} not found`,- error,- })- );- break;-- default:- res.status(405).json({ message: "Method not allowed" });- break;- }- }-}--export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(eventTypeById));diff --git a/pages/api/event-types/[id]/_auth-middleware.ts b/pages/api/event-types/[id]/_auth-middleware.tsnew file mode 100644index 00000000000..dd5fc901096--- /dev/null+++ b/pages/api/event-types/[id]/_auth-middleware.ts@@ -0,0 +1,17 @@+import type { NextApiRequest } from "next";++import { HttpError } from "@calcom/lib/http-error";++import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";++async function authMiddleware(req: NextApiRequest) {+ const { userId, isAdmin, prisma } = req;+ const { id } = schemaQueryIdParseInt.parse(req.query);+ if (isAdmin) return;+ const eventType = await prisma.eventType.findFirst({+ where: { id, users: { some: { id: userId } } },+ });+ if (!eventType) throw new HttpError({ statusCode: 401, message: "Unauthorized" });+}++export default authMiddleware;diff --git a/pages/api/event-types/[id]/_delete.ts b/pages/api/event-types/[id]/_delete.tsnew file mode 100644index 00000000000..a4fbec2e2bc--- /dev/null+++ b/pages/api/event-types/[id]/_delete.ts@@ -0,0 +1,52 @@+import type { NextApiRequest } from "next";++import { HttpError } from "@calcom/lib/http-error";+import { defaultResponder } from "@calcom/lib/server";++import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";++/**+ * @swagger+ * /event-types/{id}:+ * delete:+ * operationId: removeEventTypeById+ * summary: Remove an existing eventType+ * parameters:+ * - in: path+ * name: id+ * schema:+ * type: integer+ * required: true+ * description: ID of the eventType to delete+ * security:+ * - ApiKeyAuth: []+ * tags:+ * - event-types+ * externalDocs:+ * url: https://docs.cal.com/event-types+ * responses:+ * 201:+ * description: OK, eventType removed successfully+ * 400:+ * description: Bad request. EventType id is invalid.+ * 401:+ * description: Authorization information is missing or invalid.+ */+export async function deleteHandler(req: NextApiRequest) {+ const { prisma, query } = req;+ const { id } = schemaQueryIdParseInt.parse(query);+ await checkPermissions(req);+ await prisma.eventType.delete({ where: { id } });+ return { message: `Event Type with id: ${id} deleted successfully` };+}++async function checkPermissions(req: NextApiRequest) {+ const { userId, prisma, isAdmin } = req;+ const { id } = schemaQueryIdParseInt.parse(req.query);+ if (isAdmin) return;+ /** Only event type owners can delete it */+ const eventType = await prisma.eventType.findFirst({ where: { id, userId } });+ if (!eventType) throw new HttpError({ statusCode: 401, message: "Unauthorized" });+}++export default defaultResponder(deleteHandler);diff --git a/pages/api/event-types/[id]/_get.ts b/pages/api/event-types/[id]/_get.tsnew file mode 100644index 00000000000..5e91666eed4--- /dev/null+++ b/pages/api/event-types/[id]/_get.ts@@ -0,0 +1,44 @@+import type { NextApiRequest } from "next";++import { defaultResponder } from "@calcom/lib/server";++import { schemaAttendeeReadPublic } from "@lib/validations/attendee";+import { schemaEventTypeReadPublic } from "@lib/validations/event-type";+import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";++/**+ * @swagger+ * /event-types/{id}:+ * get:+ * operationId: getEventTypeById+ * summary: Find a eventType+ * parameters:+ * - in: path+ * name: id+ * example: 4+ * schema:+ * type: integer+ * required: true+ * description: ID of the eventType to get+ * security:+ * - ApiKeyAuth: []+ * tags:+ * - event-types+ * externalDocs:+ * url: https://docs.cal.com/event-types+ * responses:+ * 200:+ * description: OK+ * 401:+ * description: Authorization information is missing or invalid.+ * 404:+ * description: EventType was not found+ */+export async function getHandler(req: NextApiRequest) {+ const { prisma, query } = req;+ const { id } = schemaQueryIdParseInt.parse(query);+ const event_type = await prisma.eventType.findUnique({ where: { id } });+ return { event_type: schemaEventTypeReadPublic.parse(event_type) };+}++export default defaultResponder(getHandler);diff --git a/pages/api/event-types/[id]/_patch.ts b/pages/api/event-types/[id]/_patch.tsnew file mode 100644index 00000000000..28956e15df0--- /dev/null+++ b/pages/api/event-types/[id]/_patch.ts@@ -0,0 +1,54 @@+import type { NextApiRequest } from "next";++import { HttpError } from "@calcom/lib/http-error";+import { defaultResponder } from "@calcom/lib/server";++import { schemaEventTypeEditBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";+import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";++/**+ * @swagger+ * /event-types/{id}:+ * patch:+ * operationId: editEventTypeById+ * summary: Edit an existing eventType+ * parameters:+ * - in: path+ * name: id+ * schema:+ * type: integer+ * required: true+ * description: ID of the eventType to edit+ * security:+ * - ApiKeyAuth: []+ * tags:+ * - event-types+ * externalDocs:+ * url: https://docs.cal.com/event-types+ * responses:+ * 201:+ * description: OK, eventType edited successfully+ * 400:+ * description: Bad request. EventType body is invalid.+ * 401:+ * description: Authorization information is missing or invalid.+ */+export async function patchHandler(req: NextApiRequest) {+ const { prisma, query, body } = req;+ const { id } = schemaQueryIdParseInt.parse(query);+ const data = schemaEventTypeEditBodyParams.parse(body);+ await checkPermissions(req);+ const event_type = await prisma.eventType.update({ where: { id }, data });+ return { event_type: schemaEventTypeReadPublic.parse(event_type) };+}++async function checkPermissions(req: NextApiRequest) {+ const { userId, prisma, isAdmin } = req;+ const { id } = schemaQueryIdParseInt.parse(req.query);+ if (isAdmin) return;+ /** Only event type owners can modify it */+ const eventType = await prisma.eventType.findFirst({ where: { id, userId } });+ if (!eventType) throw new HttpError({ statusCode: 401, message: "Unauthorized" });+}++export default defaultResponder(patchHandler);diff --git a/pages/api/event-types/[id]/index.ts b/pages/api/event-types/[id]/index.tsnew file mode 100644index 00000000000..7d92ee29066--- /dev/null+++ b/pages/api/event-types/[id]/index.ts@@ -0,0 +1,18 @@+import { NextApiRequest, NextApiResponse } from "next";++import { defaultHandler, defaultResponder } from "@calcom/lib/server";++import { withMiddleware } from "@lib/helpers/withMiddleware";++import authMiddleware from "./_auth-middleware";++export default withMiddleware("HTTP_GET_DELETE_PATCH")(+ defaultResponder(async (req: NextApiRequest, res: NextApiResponse) => {+ await authMiddleware(req);+ return defaultHandler({+ GET: import("./_get"),+ PATCH: import("./_patch"),+ DELETE: import("./_delete"),+ })(req, res);+ })+);diff --git a/pages/api/event-types/_get.ts b/pages/api/event-types/_get.tsnew file mode 100644index 00000000000..3a3b968b8b7--- /dev/null+++ b/pages/api/event-types/_get.ts@@ -0,0 +1,42 @@+import type { Prisma } from "@prisma/client";+import type { NextApiRequest } from "next";++import { HttpError } from "@calcom/lib/http-error";+import { defaultResponder } from "@calcom/lib/server";++import { schemaEventTypeReadPublic } from "@lib/validations/event-type";+import { schemaQuerySingleOrMultipleUserIds } from "@lib/validations/shared/queryUserId";++/**+ * @swagger+ * /event-types:+ * get:+ * summary: Find all event types+ * operationId: listEventTypes+ * tags:+ * - event-types+ * externalDocs:+ * url: https://docs.cal.com/event-types+ * responses:+ * 200:+ * description: OK+ * 401:+ * description: Authorization information is missing or invalid.+ * 404:+ * description: No event types were found+ */+async function getHandler(req: NextApiRequest) {+ const { userId, isAdmin, prisma } = req;+ const args: Prisma.EventTypeFindManyArgs = isAdmin ? {} : { where: { userId } };+ /** Only admins can query other users */+ if (!isAdmin && req.query.userId) throw new HttpError({ statusCode: 401, message: "ADMIN required" });+ if (isAdmin && req.query.userId) {+ const query = schemaQuerySingleOrMultipleUserIds.parse(req.query);+ const userIds = Array.isArray(query.userId) ? query.userId : [query.userId || userId];+ args.where = { userId: { in: userIds } };+ }+ const data = await prisma.eventType.findMany(args);+ return { event_types: data.map((attendee) => schemaEventTypeReadPublic.parse(attendee)) };+}++export default defaultResponder(getHandler);diff --git a/pages/api/event-types/_post.ts b/pages/api/event-types/_post.tsnew file mode 100644index 00000000000..75faa6d5c02--- /dev/null+++ b/pages/api/event-types/_post.ts@@ -0,0 +1,79 @@+import { HttpError } from "@/../../packages/lib/http-error";+import type { Prisma } from "@prisma/client";+import type { NextApiRequest } from "next";++import { defaultResponder } from "@calcom/lib/server";++import { schemaEventTypeCreateBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";++/**+ * @swagger+ * /event-types:+ * post:+ * summary: Creates a new event type+ * operationId: addEventType+ * requestBody:+ * description: Create a new event-type related to your user or team+ * required: true+ * content:+ * application/json:+ * schema:+ * type: object+ * required:+ * - title+ * - slug+ * - length+ * - metadata+ * properties:+ * length:+ * type: number+ * example: 30+ * metadata:+ * type: object+ * example: {"smartContractAddress": "0x1234567890123456789012345678901234567890"}+ * title:+ * type: string+ * example: My Event+ * slug:+ * type: string+ * example: my-event+ * tags:+ * - event-types+ * externalDocs:+ * url: https://docs.cal.com/event-types+ * responses:+ * 201:+ * description: OK, event type created+ * 400:+ * description: Bad request. EventType body is invalid.+ * 401:+ * description: Authorization information is missing or invalid.+ */+async function postHandler(req: NextApiRequest) {+ const { userId, isAdmin, prisma } = req;+ const body = schemaEventTypeCreateBodyParams.parse(req.body);+ let args: Prisma.EventTypeCreateArgs = { data: { ...body, userId, users: { connect: { id: userId } } } };++ await checkPermissions(req);++ if (isAdmin && body.userId) args = { data: { ...body, users: { connect: { id: body.userId } } } };++ const data = await prisma.eventType.create(args);++ return {+ event_type: schemaEventTypeReadPublic.parse(data),+ message: "Event type created successfully",+ };+}++async function checkPermissions(req: NextApiRequest) {+ const { isAdmin } = req;+ const body = schemaEventTypeCreateBodyParams.parse(req.body);+ /* Non-admin users can only create event types for themselves */+ if (!isAdmin && body.userId)+ throw new HttpError({ statusCode: 401, message: "ADMIN required for `userId`" });+ /* Admin users are required to pass in a userId */+ if (isAdmin && !body.userId) throw new HttpError({ statusCode: 400, message: "`userId` required" });+}++export default defaultResponder(postHandler);diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.tsindex d5a203e67da..c07846423fa 100644--- a/pages/api/event-types/index.ts+++ b/pages/api/event-types/index.ts@@ -1,140 +1,10 @@-import type { NextApiRequest, NextApiResponse } from "next";+import { defaultHandler } from "@calcom/lib/server";import { withMiddleware } from "@lib/helpers/withMiddleware";-import { EventTypeResponse, EventTypesResponse } from "@lib/types";-import { schemaEventTypeCreateBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";-async function createOrlistAllEventTypes(- { method, body, userId, isAdmin, prisma }: NextApiRequest,- res: NextApiResponse<EventTypesResponse | EventTypeResponse>-) {- if (method === "GET") {- /**- * @swagger- * /event-types:- * get:- * summary: Find all event types- * operationId: listEventTypes- * tags:- * - event-types- * externalDocs:- * url: https://docs.cal.com/event-types- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: No event types were found- */- if (!isAdmin) {- const data = await prisma.user- .findUnique({- where: { id: userId },- rejectOnNotFound: true,- select: { eventTypes: true },- })- .catch((error) => res.status(404).json({ message: "No event types were found", error }));- // @todo: add validations back schemaReadEventType.parse- if (data) res.status(200).json({ event_types: data.eventTypes });- else- (error: Error) =>- res.status(404).json({- message: "No EventTypes were found",- error,- });- } else {- const data = await prisma.eventType.findMany({- where: {- ...(Array.isArray(body.userId)- ? { userId: { in: body.userId } }- : { userId: body.userId || userId }),- },- ...(Array.isArray(body.userId) && { orderBy: { userId: "asc" } }),- });- const event_types = data.map((eventType) => schemaEventTypeReadPublic.parse(eventType));- if (event_types) res.status(200).json({ event_types });- }- } else if (method === "POST") {- /**- * @swagger- * /event-types:- * post:- * summary: Creates a new event type- * operationId: addEventType- * requestBody:- * description: Create a new event-type related to your user or team- * required: true- * content:- * application/json:- * schema:- * type: object- * required:- * - title- * - slug- * - length- * - metadata- * properties:- * length:- * type: number- * example: 30- * metadata:- * type: object- * example: {"smartContractAddress": "0x1234567890123456789012345678901234567890"}- * title:- * type: string- * example: My Event- * slug:- * type: string- * example: my-event- * tags:- * - event-types- * externalDocs:- * url: https://docs.cal.com/event-types- * responses:- * 201:- * description: OK, event type created- * 400:- * description: Bad request. EventType body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */- const safe = schemaEventTypeCreateBodyParams.safeParse(body);- if (!safe.success) {- res.status(400).json({ message: "Invalid request body", error: safe.error });- return;- }- if (!isAdmin) {- const data = await prisma.eventType.create({- data: {- ...safe.data,- userId,- users: {- connect: {- id: userId,- },- },- },- });- const event_type = schemaEventTypeReadPublic.parse(data);- if (data) res.status(201).json({ event_type, message: "EventType created successfully" });- } else {- // if admin don't re-set userId from input- const data = await prisma.eventType.create({- data: {- ...safe.data,- ...(!safe.data.userId && { userId }),- users: {- connect: {- id: safe.data.userId || userId,- },- },- },- });- const event_type = schemaEventTypeReadPublic.parse(data);- if (data) res.status(201).json({ event_type, message: "EventType created successfully" });- }- } else res.status(405).json({ message: `Method ${method} not allowed` });-}--export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllEventTypes);+export default withMiddleware("HTTP_GET_OR_POST")(+ defaultHandler({+ GET: import("./_get"),+ POST: import("./_post"),+ })+);