Scheduling infrastructure for absolutely everyone.
fix: move all req to deconstructed
Agusti Fernandez Pardob572e4b0ffb5
diff --git a/README.md b/README.mdindex a9904ac3ff9..4bba94e69a3 100644--- a/README.md+++ b/README.md@@ -108,8 +108,6 @@ We have some shared validations which several resources require, like baseApiPar- **[*]BodyParams** which merges both `[*]BaseBodyParams.merge([*]RequiredParams);`-- **withValid[*]** which is currently not being much used because is only useful in only post endpoints (we do post/get all in same file). This would validate the req.body of a POST call to API against our BaseBodyParams validation-### Next Validations[Next-Validations Docs](https://next-validations.productsway.com/)diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.tsindex cf5c4a84722..c4fabac6526 100644--- a/lib/helpers/verifyApiKey.ts+++ b/lib/helpers/verifyApiKey.ts@@ -8,6 +8,8 @@ import prisma from "@calcom/prisma";declare module "next" {export interface NextApiRequest extends IncomingMessage {userId: number;+ body: any;+ query: { [key: string]: string | string[] };}}@@ -20,21 +22,21 @@ export const dateNotInPast = function (date: Date) {};// This verifies the apiKey and sets the user if it is valid.-export const verifyApiKey: NextMiddleware = async (req, res, next) => {- if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });+export const verifyApiKey: NextMiddleware = async ({ query: { apiKey }, ...req }, res, next) => {+ if (!apiKey) return res.status(401).json({ message: "No apiKey provided" });// We remove the prefix from the user provided api_key. If no env set default to "cal_"- const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");+ const strippedApiKey = `${apiKey}`.replace(process.env.API_KEY_PREFIX || " cal_", "");// Hash the key again before matching against the database records.const hashedKey = hashAPIKey(strippedApiKey);// Check if the hashed api key exists in database.- const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });+ const validApiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });// If we cannot find any api key. Throw a 401 Unauthorized.- if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" });- if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) {+ if (!validApiKey) return res.status(401).json({ error: "Your apiKey is not valid" });+ if (validApiKey.expiresAt && dateNotInPast(validApiKey.expiresAt)) {return res.status(401).json({ error: "This apiKey is expired" });}- if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });+ if (!validApiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });/* We save the user id in the request for later use */- req.userId = apiKey.userId;+ req.userId = validApiKey.userId;await next();};diff --git a/pages/api/availabilities/index.ts b/pages/api/availabilities/index.tsindex 25b08660719..c7b53c211d4 100644--- a/pages/api/availabilities/index.ts+++ b/pages/api/availabilities/index.ts@@ -10,7 +10,7 @@ import {} from "@lib/validations/availability";async function createOrlistAllAvailabilities(- { method, userId }: NextApiRequest,+ { method, body, userId }: NextApiRequest,res: NextApiResponse<AvailabilitiesResponse | AvailabilityResponse>) {if (method === "GET") {@@ -58,7 +58,7 @@ async function createOrlistAllAvailabilities(* 401:* description: Authorization information is missing or invalid.*/- const safe = schemaAvailabilityCreateBodyParams.safeParse(req.body);+ const safe = schemaAvailabilityCreateBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");const data = await prisma.availability.create({ data: { ...safe.data, userId } });diff --git a/pages/api/booking-references/[id].ts b/pages/api/booking-references/[id].tsindex cb0358d9019..03bc87fafb3 100644--- a/pages/api/booking-references/[id].ts+++ b/pages/api/booking-references/[id].ts@@ -27,32 +27,33 @@ export async function bookingReferenceById(if (!userWithBookings) throw new Error("User not found");const userBookingIds = userWithBookings.bookings.map((booking: { id: number }) => booking.id).flat();const bookingReference = await prisma.bookingReference.findUnique({ where: { id: safeQuery.data.id } });- if (!bookingReference) throw new Error("BookingReference not found");+ if (!bookingReference?.bookingId) throw new Error("BookingReference: bookingId not found");if (userBookingIds.includes(bookingReference.bookingId)) {switch (method) {- /**- * @swagger- * /booking-references/{id}:- * get:- * summary: Find a booking reference- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: Numeric ID of the booking reference to get- * tags:- * - booking-references- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: BookingReference was not found- */case "GET":+ /**+ * @swagger+ * /booking-references/{id}:+ * get:+ * summary: Find a booking reference+ * parameters:+ * - in: path+ * name: id+ * schema:+ * type: integer+ * required: true+ * description: Numeric ID of the booking reference to get+ * tags:+ * - booking-references+ * responses:+ * 200:+ * description: OK+ * 401:+ * description: Authorization information is missing or invalid.+ * 404:+ * description: BookingReference was not found+ */+await prisma.bookingReference.findUnique({ where: { id: safeQuery.data.id } }).then((data) => schemaBookingReferenceReadPublic.parse(data))@@ -63,30 +64,32 @@ export async function bookingReferenceById(error,}));+break;- /**- * @swagger- * /booking-references/{id}:- * patch:- * summary: Edit an existing booking reference- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: Numeric ID of the booking reference to edit- * tags:- * - booking-references- * responses:- * 201:- * description: OK, bookingReference edited successfuly- * 400:- * description: Bad request. BookingReference body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */case "PATCH":+ /**+ * @swagger+ * /booking-references/{id}:+ * patch:+ * summary: Edit an existing booking reference+ * parameters:+ * - in: path+ * name: id+ * schema:+ * type: integer+ * required: true+ * description: Numeric ID of the booking reference to edit+ * tags:+ * - booking-references+ * responses:+ * 201:+ * description: OK, bookingReference edited successfuly+ * 400:+ * description: Bad request. BookingReference body is invalid.+ * 401:+ * description: Authorization information is missing or invalid.+ */+const safeBody = schemaBookingEditBodyParams.safeParse(body);if (!safeBody.success) {throw new Error("Invalid request body");diff --git a/pages/api/booking-references/index.ts b/pages/api/booking-references/index.tsindex 87cbe25cdcf..c228673240b 100644--- a/pages/api/booking-references/index.ts+++ b/pages/api/booking-references/index.ts@@ -75,6 +75,7 @@ async function createOrlistAllBookingReferences(throw new Error("User not found");}const userBookingIds = userWithBookings.bookings.map((booking: { id: number }) => booking.id).flat();+ if (!safe.data.bookingId) throw new Error("BookingReference: bookingId not found");if (!userBookingIds.includes(safe.data.bookingId)) res.status(401).json({ message: "Unauthorized" });else {const booking_reference = await prisma.bookingReference.create({diff --git a/pages/api/bookings/index.ts b/pages/api/bookings/index.tsindex 57a774a916a..bd1595ff6c8 100644--- a/pages/api/bookings/index.ts+++ b/pages/api/bookings/index.ts@@ -7,7 +7,7 @@ import { BookingResponse, BookingsResponse } from "@lib/types";import { schemaBookingCreateBodyParams, schemaBookingReadPublic } from "@lib/validations/booking";async function createOrlistAllBookings(- { method, userId }: NextApiRequest,+ { method, body, userId }: NextApiRequest,res: NextApiResponse<BookingsResponse | BookingResponse>) {if (method === "GET") {@@ -51,7 +51,7 @@ async function createOrlistAllBookings(* 401:* description: Authorization information is missing or invalid.*/- const safe = schemaBookingCreateBodyParams.safeParse(req.body);+ const safe = schemaBookingCreateBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");const data = await prisma.booking.create({ data: { ...safe.data, userId } });diff --git a/pages/api/payments/index.ts b/pages/api/payments/index.tsindex 0c6eae0f85b..d758421f463 100644--- a/pages/api/payments/index.ts+++ b/pages/api/payments/index.ts@@ -21,9 +21,7 @@ import { schemaPaymentPublic } from "@lib/validations/payment";* 404:* description: No payments were found*/-async function allPayments(req: NextApiRequest, res: NextApiResponse<PaymentsResponse>) {- const userId = req.userId;-+async function allPayments({ userId }: NextApiRequest, res: NextApiResponse<PaymentsResponse>) {const userWithBookings = await prisma.user.findUnique({where: { id: userId },include: { bookings: true },diff --git a/pages/api/schedules/[id].ts b/pages/api/schedules/[id].tsindex af63d8af2bb..38066c4ab85 100644--- a/pages/api/schedules/[id].ts+++ b/pages/api/schedules/[id].ts@@ -10,12 +10,13 @@ import {withValidQueryIdTransformParseInt,} from "@lib/validations/shared/queryIdTransformParseInt";-export async function scheduleById(req: NextApiRequest, res: NextApiResponse<ScheduleResponse>) {- const { method, query, body } = req;+export async function scheduleById(+ { method, query, body, userId }: NextApiRequest,+ res: NextApiResponse<ScheduleResponse>+) {const safeQuery = schemaQueryIdParseInt.safeParse(query);const safeBody = schemaScheduleBodyParams.safeParse(body);if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);- const userId = req.userId;const userSchedules = await prisma.schedule.findMany({ where: { userId } });const userScheduleIds = userSchedules.map((schedule) => schedule.id);if (!userScheduleIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });diff --git a/pages/api/schedules/index.ts b/pages/api/schedules/index.tsindex 5da47e226c1..04dbc6b1a1e 100644--- a/pages/api/schedules/index.ts+++ b/pages/api/schedules/index.ts@@ -7,12 +7,9 @@ import { ScheduleResponse, SchedulesResponse } from "@lib/types";import { schemaScheduleBodyParams, schemaSchedulePublic } from "@lib/validations/schedule";async function createOrlistAllSchedules(- req: NextApiRequest,+ { method, body, userId }: NextApiRequest,res: NextApiResponse<SchedulesResponse | ScheduleResponse>) {- const { method } = req;- const userId = req.userId;-if (method === "GET") {/*** @swagger@@ -54,7 +51,7 @@ async function createOrlistAllSchedules(* 401:* description: Authorization information is missing or invalid.*/- const safe = schemaScheduleBodyParams.safeParse(req.body);+ const safe = schemaScheduleBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");const data = await prisma.schedule.create({ data: { ...safe.data, userId } });const schedule = schemaSchedulePublic.parse(data);diff --git a/pages/api/selected-calendars/[id].ts b/pages/api/selected-calendars/[id].tsindex 10fb737cf9e..de4d7a55709 100644--- a/pages/api/selected-calendars/[id].ts+++ b/pages/api/selected-calendars/[id].ts@@ -11,16 +11,14 @@ import {import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/shared/queryIdString";export async function selectedCalendarById(- req: NextApiRequest,+ { method, query, body, userId }: NextApiRequest,res: NextApiResponse<SelectedCalendarResponse>) {- const { method, query, body } = req;const safeQuery = schemaQueryIdAsString.safeParse(query);const safeBody = schemaSelectedCalendarBodyParams.safeParse(body);if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);// This is how we set the userId and externalId in the query for managing compoundId.const [paramUserId, integration, externalId] = safeQuery.data.id.split("_");- const userId = req.userId;if (userId !== parseInt(paramUserId)) res.status(401).json({ message: "Unauthorized" });else {switch (method) {diff --git a/pages/api/selected-calendars/index.ts b/pages/api/selected-calendars/index.tsindex 758d663b8f7..cbf2e94b814 100644--- a/pages/api/selected-calendars/index.ts+++ b/pages/api/selected-calendars/index.ts@@ -10,7 +10,7 @@ import {} from "@lib/validations/selected-calendar";async function createOrlistAllSelectedCalendars(- { method, userId }: NextApiRequest,+ { method, body, userId }: NextApiRequest,res: NextApiResponse<SelectedCalendarsResponse | SelectedCalendarResponse>) {if (method === "GET") {@@ -67,7 +67,7 @@ async function createOrlistAllSelectedCalendars(* 401:* description: Authorization information is missing or invalid.*/- const safe = schemaSelectedCalendarBodyParams.safeParse(req.body);+ const safe = schemaSelectedCalendarBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");// Create new selectedCalendar connecting it to current userIdconst data = await prisma.selectedCalendar.create({diff --git a/pages/api/teams/[id].ts b/pages/api/teams/[id].tsindex d3e971d4877..e49277a1435 100644--- a/pages/api/teams/[id].ts+++ b/pages/api/teams/[id].ts@@ -68,12 +68,13 @@ import { schemaTeamBodyParams, schemaTeamPublic } from "@lib/validations/team";* 401:* description: Authorization information is missing or invalid.*/-export async function teamById(req: NextApiRequest, res: NextApiResponse<TeamResponse>) {- const { method, query, body } = req;+export async function teamById(+ { method, query, body, userId }: NextApiRequest,+ res: NextApiResponse<TeamResponse>+) {const safeQuery = schemaQueryIdParseInt.safeParse(query);const safeBody = schemaTeamBodyParams.safeParse(body);if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);- const userId = req.userId;const userWithMemberships = await prisma.membership.findMany({where: { userId: userId },});diff --git a/pages/api/teams/index.ts b/pages/api/teams/index.tsindex e5ae852dd84..75aabd47b9d 100644--- a/pages/api/teams/index.ts+++ b/pages/api/teams/index.ts@@ -7,36 +7,26 @@ import { TeamResponse, TeamsResponse } from "@lib/types";import { schemaMembershipPublic } from "@lib/validations/membership";import { schemaTeamBodyParams, schemaTeamPublic } from "@lib/validations/team";-/**- * @swagger- * /teams:- * get:- * summary: Find all teams- * tags:- * - teams- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: No teams were found- * post:- * summary: Creates a new team- * tags:- * - teams- * responses:- * 201:- * description: OK, team created- * 400:- * description: Bad request. Team body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */-async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse<TeamsResponse | TeamResponse>) {- const { method } = req;- const userId = req.userId;+async function createOrlistAllTeams(+ { method, body, userId }: NextApiRequest,+ res: NextApiResponse<TeamsResponse | TeamResponse>+) {if (method === "GET") {+ /**+ * @swagger+ * /teams:+ * get:+ * summary: Find all teams+ * tags:+ * - teams+ * responses:+ * 200:+ * description: OK+ * 401:+ * description: Authorization information is missing or invalid.+ * 404:+ * description: No teams were found+ */const userWithMemberships = await prisma.membership.findMany({where: { userId: userId },});@@ -50,7 +40,22 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse<Teerror,});} else if (method === "POST") {- const safe = schemaTeamBodyParams.safeParse(req.body);+ /**+ * @swagger+ * /teams:+ * post:+ * summary: Creates a new team+ * tags:+ * - teams+ * responses:+ * 201:+ * description: OK, team created+ * 400:+ * description: Bad request. Team body is invalid.+ * 401:+ * description: Authorization information is missing or invalid.+ */+ const safe = schemaTeamBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");const team = await prisma.team.create({ data: safe.data });// We're also creating the relation membership of team ownership in this call.diff --git a/pages/api/users/[id].ts b/pages/api/users/[id].tsindex 6b3e7ec7840..3093b43cfc7 100644--- a/pages/api/users/[id].ts+++ b/pages/api/users/[id].ts@@ -71,8 +71,7 @@ import { schemaUserEditBodyParams, schemaUserReadPublic } from "@lib/validations* 401:* description: Authorization information is missing or invalid.*/-export async function userById(req: NextApiRequest, res: NextApiResponse<any>) {- const { method, query, body, userId } = req;+export async function userById({ method, query, body, userId }: NextApiRequest, res: NextApiResponse<any>) {const safeQuery = schemaQueryIdParseInt.safeParse(query);console.log(body);if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);diff --git a/pages/api/users/index.ts b/pages/api/users/index.tsindex 5f6c64d6041..046d456de96 100644--- a/pages/api/users/index.ts+++ b/pages/api/users/index.ts@@ -22,8 +22,7 @@ import { schemaUserReadPublic } from "@lib/validations/user";* 404:* description: No users were found*/-async function allUsers(req: NextApiRequest, res: NextApiResponse<UsersResponse>) {- const userId = req.userId;+async function allUsers({ userId }: NextApiRequest, res: NextApiResponse<UsersResponse>) {const data = await prisma.user.findMany({where: {id: userId,diff --git a/templates/endpoints/[id]/delete.ts b/templates/endpoints/[id]/delete.tsindex 908e74b7d59..133554ac259 100644--- a/templates/endpoints/[id]/delete.ts+++ b/templates/endpoints/[id]/delete.ts@@ -32,9 +32,9 @@ import {* 401:* description: Authorization information is missing or invalid.*/-export async function deleteResource(req: NextApiRequest, res: NextApiResponse<BaseResponse>) {- const safe = schemaQueryIdParseInt.safeParse(req.query);- if (!safe.success) throw new Error("Invalid request query", safe.error);+export async function deleteResource({query}: NextApiRequest, res: NextApiResponse<BaseResponse>) {+ const safe = schemaQueryIdParseInt.safeParse(query);+ if (!safe.success) throw new Error("Invalid request query");const data = await prisma.resource.delete({ where: { id: safe.data.id } });diff --git a/templates/endpoints/[id]/edit.ts b/templates/endpoints/[id]/edit.tsindex 43cb6c8f8ed..e72198d82eb 100644--- a/templates/endpoints/[id]/edit.ts+++ b/templates/endpoints/[id]/edit.ts@@ -33,9 +33,9 @@ import {* 401:* description: Authorization information is missing or invalid.*/-export async function editResource(req: NextApiRequest, res: NextApiResponse<ResourceResponse>) {- const safeQuery = schemaQueryIdParseInt.safeParse(req.query);- const safeBody = schemaResourceBodyParams.safeParse(req.body);+export async function editResource({query, body}: NextApiRequest, res: NextApiResponse<ResourceResponse>) {+ const safeQuery = schemaQueryIdParseInt.safeParse(query);+ const safeBody = schemaResourceBodyParams.safeParse(body);if (!safeQuery.success || !safeBody.success) throw new Error("Invalid request");const resource = await prisma.resource.update({diff --git a/templates/endpoints/[id]/index.ts b/templates/endpoints/[id]/index.tsindex c9b1d851526..4a0656d3b58 100644--- a/templates/endpoints/[id]/index.ts+++ b/templates/endpoints/[id]/index.ts@@ -33,8 +33,8 @@ import {* 404:* description: Resource was not found*/-export async function resourceById(req: NextApiRequest, res: NextApiResponse<ResourceResponse>) {- const safe = schemaQueryIdParseInt.safeParse(req.query);+export async function resourceById({query}: NextApiRequest, res: NextApiResponse<ResourceResponse>) {+ const safe = schemaQueryIdParseInt.safeParse(query);if (!safe.success) throw new Error("Invalid request query");const resource = await prisma.resource.findUnique({ where: { id: safe.data.id } });diff --git a/templates/endpoints/get_all_and_post.ts b/templates/endpoints/get_all_and_post.tsindex d20075e52c7..e21dc8bb9dd 100644--- a/templates/endpoints/get_all_and_post.ts+++ b/templates/endpoints/get_all_and_post.ts@@ -6,6 +6,12 @@ import { withMiddleware } from "@lib/helpers/withMiddleware";import { PaymentResponse, PaymentsResponse } from "@lib/types";import { schemaPaymentBodyParams, schemaPaymentPublic } from "@lib/validations/payment";+async function createOrlistAllPayments(+ {method, body}: NextApiRequest,+ res: NextApiResponse<PaymentsResponse | PaymentResponse>+) {+ if (method === "GET") {+/*** @swagger* /v1/payments:@@ -21,6 +27,21 @@ import { schemaPaymentBodyParams, schemaPaymentPublic } from "@lib/validations/p* description: Authorization information is missing or invalid.* 404:* description: No payments were found+ */+ const payments = await prisma.payment.findMany();+ const data = payments.map((payment) => schemaPaymentPublic.parse(payment));+ if (data) res.status(200).json({ data });+ else+ (error: Error) =>+ res.status(404).json({+ message: "No Payments were found",+ error,+ });+ } else if (method === "POST") {++/**+ * @swagger+ * /v1/payments:* post:* summary: Creates a new payment@@ -34,23 +55,7 @@ import { schemaPaymentBodyParams, schemaPaymentPublic } from "@lib/validations/p* 401:* description: Authorization information is missing or invalid.*/-async function createOrlistAllPayments(- req: NextApiRequest,- res: NextApiResponse<PaymentsResponse | PaymentResponse>-) {- const { method } = req;- if (method === "GET") {- const payments = await prisma.payment.findMany();- const data = payments.map((payment) => schemaPaymentPublic.parse(payment));- if (data) res.status(200).json({ data });- else- (error: Error) =>- res.status(404).json({- message: "No Payments were found",- error,- });- } else if (method === "POST") {- const safe = schemaPaymentBodyParams.safeParse(req.body);+ const safe = schemaPaymentBodyParams.safeParse(body);if (!safe.success) throw new Error("Invalid request body");const payment = await prisma.payment.create({ data: safe.data });diff --git a/templates/endpoints/post.ts b/templates/endpoints/post.tsindex 3f5b7403d74..896c09e6918 100644--- a/templates/endpoints/post.ts+++ b/templates/endpoints/post.ts@@ -29,9 +29,9 @@ import { schemaResourceBodyParams, schemaResourcePublic, withValidResource } fro* 401:* description: Authorization information is missing or invalid.*/-async function createResource(req: NextApiRequest, res: NextApiResponse<ResourceResponse>) {- const safe = schemaResourceBodyParams.safeParse(req.body);- if (!safe.success) throw new Error("Invalid request body", safe.error);+async function createResource({body}: NextApiRequest, res: NextApiResponse<ResourceResponse>) {+ const safe = schemaResourceBodyParams.safeParse(body);+ if (!safe.success) throw new Error("Invalid request body");const resource = await prisma.resource.create({ data: safe.data });const data = schemaResourcePublic.parse(resource);diff --git a/types.d.ts b/types.d.tsindex 9a7af651d13..2abf07e4c1e 100644--- a/types.d.ts+++ b/types.d.ts@@ -1 +1,2 @@declare module "modify-response-middleware";+