Skip to content

Scheduling infrastructure for absolutely everyone.

Splits user endpoints by method

zomars0f72a9084a78
diff --git a/pages/api/users/[id]/_delete.ts b/pages/api/users/[id]/_delete.ts
new file mode 100644
index 00000000000..ce04999eea8
--- /dev/null
+++ b/pages/api/users/[id]/_delete.ts
@@ -0,0 +1,43 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+import prisma from "@calcom/prisma";
+
+import { isAdminGuard } from "@lib/utils/isAdmin";
+import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";
+
+/**
+ * @swagger
+ * /users/{id}:
+ * delete:
+ * summary: Remove an existing user
+ * operationId: removeUserById
+ * parameters:
+ * - in: path
+ * name: id
+ * example: 1
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to delete
+ * tags:
+ * - users
+ * responses:
+ * 201:
+ * description: OK, user removed successfuly
+ * 400:
+ * description: Bad request. User id is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+export async function deleteHandler(req: NextApiRequest) {
+ const query = schemaQueryIdParseInt.parse(req.query);
+ const isAdmin = await isAdminGuard(req.userId);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.id !== req.userId) throw new HttpError({ statusCode: 401, message: "Unauthorized" });
+ await prisma.user.delete({ where: { id: query.id } });
+ return { message: `User with id: ${query.id} deleted successfully` };
+}
+
+export default defaultResponder(deleteHandler);
diff --git a/pages/api/users/[id]/_get.ts b/pages/api/users/[id]/_get.ts
new file mode 100644
index 00000000000..443b935e9c9
--- /dev/null
+++ b/pages/api/users/[id]/_get.ts
@@ -0,0 +1,45 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+import prisma from "@calcom/prisma";
+
+import { isAdminGuard } from "@lib/utils/isAdmin";
+import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";
+import { schemaUserReadPublic } from "@lib/validations/user";
+
+/**
+ * @swagger
+ * /users/{id}:
+ * get:
+ * summary: Find a user, returns your user if regular user.
+ * operationId: getUserById
+ * parameters:
+ * - in: path
+ * name: id
+ * example: 4
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to get
+ * tags:
+ * - users
+ * responses:
+ * 200:
+ * description: OK
+ * 401:
+ * description: Authorization information is missing or invalid.
+ * 404:
+ * description: User was not found
+ */
+export async function getHandler(req: NextApiRequest) {
+ const query = schemaQueryIdParseInt.parse(req.query);
+ const isAdmin = await isAdminGuard(req.userId);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.id !== req.userId) throw new HttpError({ statusCode: 401, message: "Unauthorized" });
+ const data = await prisma.user.findUnique({ where: { id: query.id } });
+ const user = schemaUserReadPublic.parse(data);
+ return { user };
+}
+
+export default defaultResponder(getHandler);
diff --git a/pages/api/users/[id]/_patch.ts b/pages/api/users/[id]/_patch.ts
new file mode 100644
index 00000000000..a6551609e70
--- /dev/null
+++ b/pages/api/users/[id]/_patch.ts
@@ -0,0 +1,82 @@
+import type { NextApiRequest } from "next";
+
+import { HttpError } from "@calcom/lib/http-error";
+import { defaultResponder } from "@calcom/lib/server";
+import prisma from "@calcom/prisma";
+
+import { isAdminGuard } from "@lib/utils/isAdmin";
+import { schemaQueryIdParseInt } from "@lib/validations/shared/queryIdTransformParseInt";
+import { schemaUserEditBodyParams, schemaUserReadPublic } from "@lib/validations/user";
+
+/**
+ * @swagger
+ * /users/{id}:
+ * patch:
+ * summary: Edit an existing user
+ * operationId: editUserById
+ * requestBody:
+ * description: Edit an existing attendee related to one of your bookings
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * weekStart:
+ * type: string
+ * enum: [Monday, Sunday, Saturday]
+ * example: Monday
+ * brandColor:
+ * type: string
+ * example: "#FF000F"
+ * darkBrandColor:
+ * type: string
+ * example: "#000000"
+ * timeZone:
+ * type: string
+ * example: Europe/London
+ * parameters:
+ * - in: path
+ * name: id
+ * example: 4
+ * schema:
+ * type: integer
+ * required: true
+ * description: ID of the user to edit
+ * tags:
+ * - users
+ * responses:
+ * 201:
+ * description: OK, user edited successfuly
+ * 400:
+ * description: Bad request. User body is invalid.
+ * 401:
+ * description: Authorization information is missing or invalid.
+ */
+export async function patchHandler(req: NextApiRequest) {
+ const query = schemaQueryIdParseInt.parse(req.query);
+ const isAdmin = await isAdminGuard(req.userId);
+ // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
+ if (!isAdmin && query.id !== req.userId) throw new HttpError({ statusCode: 401, message: "Unauthorized" });
+
+ const body = schemaUserEditBodyParams.parse(req.body);
+ const userSchedules = await prisma.schedule.findMany({
+ where: { userId: req.userId },
+ });
+ const userSchedulesIds = userSchedules.map((schedule) => schedule.id);
+ // @note: here we make sure user can only make as default his own scheudles
+ if (body.defaultScheduleId && !userSchedulesIds.includes(Number(body.defaultScheduleId))) {
+ throw new HttpError({
+ statusCode: 400,
+ message: "Bad request: Invalid default schedule id",
+ });
+ }
+ const data = await prisma.user.update({
+ where: { id: req.userId },
+ data: body,
+ });
+ const user = schemaUserReadPublic.parse(data);
+ return { user };
+}
+
+export default defaultResponder(patchHandler);
diff --git a/pages/api/users/[id]/index.ts b/pages/api/users/[id]/index.ts
index 65b864c6526..7d8887e5d16 100644
--- a/pages/api/users/[id]/index.ts
+++ b/pages/api/users/[id]/index.ts
@@ -1,186 +1,14 @@
-import type { NextApiRequest, NextApiResponse } from "next";
-
-import prisma from "@calcom/prisma";
+import { defaultHandler } from "@/../../packages/lib/server";
import { withMiddleware } from "@lib/helpers/withMiddleware";
-import type { UserResponse } from "@lib/types";
-import { isAdminGuard } from "@lib/utils/isAdmin";
-import {
- schemaQueryIdParseInt,
- withValidQueryIdTransformParseInt,
-} from "@lib/validations/shared/queryIdTransformParseInt";
-import { schemaUserEditBodyParams, schemaUserReadPublic } from "@lib/validations/user";
-
-export async function userById(
- { method, query, body, userId }: NextApiRequest,
- res: NextApiResponse<UserResponse>
-) {
- const safeQuery = schemaQueryIdParseInt.safeParse(query);
- console.log(body);
- if (!safeQuery.success) {
- res.status(400).json({ message: "Your query was invalid" });
- return;
- }
- const isAdmin = await isAdminGuard(userId);
- // Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any user
- if (!isAdmin) {
- if (safeQuery.data.id !== userId) res.status(401).json({ message: "Unauthorized" });
- } else {
- switch (method) {
- case "GET":
- /**
- * @swagger
- * /users/{id}:
- * get:
- * summary: Find a user, returns your user if regular user.
- * operationId: getUserById
- * parameters:
- * - in: path
- * name: id
- * example: 4
- * schema:
- * type: integer
- * required: true
- * description: ID of the user to get
- * tags:
- * - users
- * responses:
- * 200:
- * description: OK
- * 401:
- * description: Authorization information is missing or invalid.
- * 404:
- * description: User was not found
- */
-
- await prisma.user
- .findUnique({ where: { id: safeQuery.data.id } })
- .then((data) => schemaUserReadPublic.parse(data))
- .then((user) => res.status(200).json({ user }))
- .catch((error: Error) =>
- res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
- );
- break;
- case "PATCH":
- /**
- * @swagger
- * /users/{id}:
- * patch:
- * summary: Edit an existing user
- * operationId: editUserById
- * requestBody:
- * description: Edit an existing attendee related to one of your bookings
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * weekStart:
- * type: string
- * enum: [Monday, Sunday, Saturday]
- * example: Monday
- * brandColor:
- * type: string
- * example: "#FF000F"
- * darkBrandColor:
- * type: string
- * example: "#000000"
- * timeZone:
- * type: string
- * example: Europe/London
- * parameters:
- * - in: path
- * name: id
- * example: 4
- * schema:
- * type: integer
- * required: true
- * description: ID of the user to edit
- * tags:
- * - users
- * responses:
- * 201:
- * description: OK, user edited successfuly
- * 400:
- * description: Bad request. User body is invalid.
- * 401:
- * description: Authorization information is missing or invalid.
- */
-
- const safeBody = schemaUserEditBodyParams.safeParse(body);
- if (!safeBody.success) {
- res.status(400).json({ message: "Bad request", error: safeBody.error });
-
- return;
- }
- const userSchedules = await prisma.schedule.findMany({
- where: { userId },
- });
- const userSchedulesIds = userSchedules.map((schedule) => schedule.id);
- // @note: here we make sure user can only make as default his own scheudles
- if (
- safeBody?.data?.defaultScheduleId &&
- !userSchedulesIds.includes(Number(safeBody?.data?.defaultScheduleId))
- ) {
- res.status(400).json({
- message: "Bad request: Invalid default schedule id",
- });
- return;
- }
- await prisma.user
- .update({
- where: { id: userId },
- data: safeBody.data,
- })
- .then((data) => schemaUserReadPublic.parse(data))
- .then((user) => res.status(200).json({ user }))
- .catch((error: Error) =>
- res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
- );
- break;
-
- /**
- * @swagger
- * /users/{id}:
- * delete:
- * summary: Remove an existing user
- * operationId: removeUserById
- * parameters:
- * - in: path
- * name: id
- * example: 1
- * schema:
- * type: integer
- * required: true
- * description: ID of the user to delete
- * tags:
- * - users
- * responses:
- * 201:
- * description: OK, user removed successfuly
- * 400:
- * description: Bad request. User id is invalid.
- * 401:
- * description: Authorization information is missing or invalid.
- */
-
- case "DELETE":
- await prisma.user
- .delete({ where: { id: safeQuery.data.id } })
- .then(() =>
- res.status(200).json({ message: `User with id: ${safeQuery.data.id} deleted successfully` })
- )
- .catch((error: Error) =>
- res.status(404).json({ message: `User 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(userById));
+import { withValidQueryIdTransformParseInt } from "@lib/validations/shared/queryIdTransformParseInt";
+
+export default withMiddleware("HTTP_GET_DELETE_PATCH")(
+ withValidQueryIdTransformParseInt(
+ defaultHandler({
+ GET: import("./_get"),
+ PATCH: import("./_patch"),
+ DELETE: import("./_delete"),
+ })
+ )
+);