Scheduling infrastructure for absolutely everyone.
fix: userId not, id remove templates stall
Agusti Fernandez Pardo04b9b71310f2
diff --git a/lib/utils/webhookSubscriptions.ts b/lib/utils/webhookSubscriptions.tsindex e53b15e7c5f..af185248b32 100644--- a/lib/utils/webhookSubscriptions.ts+++ b/lib/utils/webhookSubscriptions.ts@@ -1,6 +1,4 @@-import { WebhookTriggerEvents } from "@prisma/client";--import prisma from "@calcom/prisma";+import { WebhookTriggerEvents, PrismaClient } from "@prisma/client";export type GetSubscriberOptions = {userId: number;@@ -8,7 +6,7 @@ export type GetSubscriberOptions = {triggerEvent: WebhookTriggerEvents;};/** @note will this not work with custom prisma? since we're importing prisma directly and not passing it from request here **/-const getWebhooks = async (options: GetSubscriberOptions) => {+const getWebhooks = async (options: GetSubscriberOptions, prisma: PrismaClient) => {const { userId, eventTypeId } = options;const allWebhooks = await prisma.webhook.findMany({where: {diff --git a/lib/validations/shared/queryUserId.ts b/lib/validations/shared/queryUserId.tsindex cbe6e282d27..94a7700003d 100644--- a/lib/validations/shared/queryUserId.ts+++ b/lib/validations/shared/queryUserId.ts@@ -13,3 +13,8 @@ export const schemaQueryUserId = baseApiParams.transform((id) => parseInt(id)),}).strict();+export const withValidQueryUserId = withValidation({+ schema: schemaQueryUserId,+ type: "Zod",+ mode: "query",+});diff --git a/pages/api/bookings/index.ts b/pages/api/bookings/index.tsindex fb1fd347aac..b70e059d8bd 100644--- a/pages/api/bookings/index.ts+++ b/pages/api/bookings/index.ts@@ -142,7 +142,7 @@ async function createOrlistAllBookings(};console.log(`subscriberOptions: ${subscriberOptions}`);- const subscribers = await getWebhooks(subscriberOptions);+ const subscribers = await getWebhooks(subscriberOptions, prisma);console.log(`subscribers: ${subscribers}`);const bookingId = booking?.id;const promises = subscribers.map((sub) =>diff --git a/pages/api/users/[userId]/_delete.ts b/pages/api/users/[userId]/_delete.tsindex ac15975931e..0f5c208e2ae 100644--- a/pages/api/users/[userId]/_delete.ts+++ b/pages/api/users/[userId]/_delete.ts@@ -2,7 +2,6 @@ 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 { schemaQueryUserId } from "@lib/validations/shared/queryUserId";@@ -32,6 +31,7 @@ import { schemaQueryUserId } from "@lib/validations/shared/queryUserId";* description: Authorization information is missing or invalid.*/export async function deleteHandler(req: NextApiRequest) {+ const { prisma } = req;const query = schemaQueryUserId.parse(req.query);const isAdmin = await isAdminGuard(req.userId, req.prisma);// Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any userdiff --git a/pages/api/users/[userId]/_get.ts b/pages/api/users/[userId]/_get.tsindex 2fda8ddc916..76b2603a893 100644--- a/pages/api/users/[userId]/_get.ts+++ b/pages/api/users/[userId]/_get.ts@@ -2,7 +2,6 @@ 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 { schemaQueryUserId } from "@lib/validations/shared/queryUserId";@@ -33,6 +32,8 @@ import { schemaUserReadPublic } from "@lib/validations/user";* description: User was not found*/export async function getHandler(req: NextApiRequest) {+ const { prisma } = req;+const query = schemaQueryUserId.parse(req.query);const isAdmin = await isAdminGuard(req.userId, req.prisma);// Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any userdiff --git a/pages/api/users/[userId]/_patch.ts b/pages/api/users/[userId]/_patch.tsindex 58efa5773b1..b7bf27c47f1 100644--- a/pages/api/users/[userId]/_patch.ts+++ b/pages/api/users/[userId]/_patch.ts@@ -2,7 +2,6 @@ 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 { schemaQueryUserId } from "@lib/validations/shared/queryUserId";@@ -54,6 +53,7 @@ import { schemaUserEditBodyParams, schemaUserReadPublic } from "@lib/validations* description: Authorization information is missing or invalid.*/export async function patchHandler(req: NextApiRequest) {+ const { prisma } = req;const query = schemaQueryUserId.parse(req.query);const isAdmin = await isAdminGuard(req.userId, req.prisma);// Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any userdiff --git a/pages/api/users/[userId]/index.ts b/pages/api/users/[userId]/index.tsindex 7d8887e5d16..66c0e9b25c8 100644--- a/pages/api/users/[userId]/index.ts+++ b/pages/api/users/[userId]/index.ts@@ -1,10 +1,10 @@-import { defaultHandler } from "@/../../packages/lib/server";+import { defaultHandler } from "@calcom/lib/server";import { withMiddleware } from "@lib/helpers/withMiddleware";-import { withValidQueryIdTransformParseInt } from "@lib/validations/shared/queryIdTransformParseInt";+import { withValidQueryUserId } from "@lib/validations/shared/queryUserId";export default withMiddleware("HTTP_GET_DELETE_PATCH")(- withValidQueryIdTransformParseInt(+ withValidQueryUserId(defaultHandler({GET: import("./_get"),PATCH: import("./_patch"),diff --git a/pages/api/users/_get.ts b/pages/api/users/_get.tsindex 7f90ba8a27e..42ec41ecfbe 100644--- a/pages/api/users/_get.ts+++ b/pages/api/users/_get.ts@@ -1,7 +1,6 @@import type { NextApiRequest } from "next";import { defaultResponder } from "@calcom/lib/server";-import prisma from "@calcom/prisma";import { isAdminGuard } from "@lib/utils/isAdmin";import { schemaUsersReadPublic } from "@lib/validations/user";diff --git a/pages/api/users/_post.ts b/pages/api/users/_post.tsindex 2217c491276..8809aa7e8a0 100644--- a/pages/api/users/_post.ts+++ b/pages/api/users/_post.ts@@ -1,13 +1,13 @@-import { HttpError } from "@/../../packages/lib/http-error";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 { schemaUserCreateBodyParams } from "@lib/validations/user";async function postHandler(req: NextApiRequest) {+ const { prisma } = req;const isAdmin = await isAdminGuard(req.userId, req.prisma);// If user is not ADMIN, return unauthorized.if (!isAdmin) throw new HttpError({ statusCode: 401, message: "You are not authorized" });diff --git a/templates/README.md b/templates/README.mddeleted file mode 100644index 3a171b93189..00000000000--- a/templates/README.md+++ /dev/null@@ -1,49 +0,0 @@-# How to add a new model or endpoint--Basically there's three places of the codebase you need to think about for each feature.--/pages/api/--- This is the most important one, and where your endpoint will live. You will leverage nextjs dynamic routes and expose one file for each endpoint you want to support ideally.--## How the codebase is organized.--## The example resource -model- and it's endpoints--### `pages/api/endpoint/`--| Method | route | action |-| ------ | --------------------------- | ------------------------- |-| GET | pages/api/endpoint/index.ts | Read All of your resource |-| POST | pages/api/endpoint/new.ts | Create new resource |--### `pages/api/endpoint/[id]/`--| Method | route | action |-| ------ | --------------------------------- | ------------------------- |-| GET | pages/api/endpoint/[id]/index.ts | Read All of your resource |-| PATCH | pages/api/endpoint/[id]/edit.ts | Create new resource |-| DELETE | pages/api/endpoint/[id]/delete.ts | Create new resource |--## `/tests/`--This is where all your endpoint's tests live, we mock prisma calls. We aim for at least 50% global coverage. Please test each of your endpoints.--### `/tests/endpoint/`--| route | action |-| -------------------------------------- | ---------------------------------------------- |-| /tests/endpoint/resource.index.test.ts | Test for your pages/api/endpoint/index.ts file |-| tests/endpoint/resource.new.test.ts | Create new resource |--### `/tests/endpoint/[id]/`--| route | action |-| ---------------------------------------------- | ------------------------- |-| `/tests/endpoint/[id]/resource.index.test.ts` | Read All of your resource |-| `/tests/endpoint/[id]/resource.edit.test.ts` | Create new resource |-| `/tests/endpoint/[id]/resource.delete.test.ts` | Create new resource |--## `/lib/validations/yourEndpoint.ts`--- This is where our model validations, live, we try to make a 1:1 for db models, and also extract out any re-usable code into the /lib/validations/shared/ sub-folder.diff --git a/templates/endpoints/[id]/delete.ts b/templates/endpoints/[id]/delete.tsdeleted file mode 100644index 39e026f4189..00000000000--- a/templates/endpoints/[id]/delete.ts+++ /dev/null@@ -1,50 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import type { BaseResponse } from "@lib/types";-import {- schemaQueryIdParseInt,- withValidQueryIdTransformParseInt,-} from "@lib/validations/shared/queryIdTransformParseInt";--/**- * @swagger- * /v1/resources/{id}/delete:- * delete:- * summary: Remove an existing resource- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: ID of the resource to delete-- * tags:- * - resources- * responses:- * 201:- * description: OK, resource removed successfuly- * 400:- * description: Bad request. Resource id is invalid.- * 401:- * description: Authorization information is missing or invalid.- */-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 } });-- if (data) res.status(200).json({ message: `Resource with id: ${safe.data.id} deleted successfully` });- else- (error: Error) =>- res.status(400).json({- message: `Resource with id: ${safe.data.id} was not able to be processed`,- error,- });-}--export default withMiddleware("HTTP_DELETE")(withValidQueryIdTransformParseInt(deleteResource));diff --git a/templates/endpoints/[id]/edit.ts b/templates/endpoints/[id]/edit.tsdeleted file mode 100644index cb4b1f05c5b..00000000000--- a/templates/endpoints/[id]/edit.ts+++ /dev/null@@ -1,58 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import type { ResourceResponse } from "@lib/types";-import { schemaResourceBodyParams, schemaResourcePublic, withValidResource } from "@lib/validations/resource";-import {- schemaQueryIdParseInt,- withValidQueryIdTransformParseInt,-} from "@lib/validations/shared/queryIdTransformParseInt";--/**- * @swagger- * /v1/resources/{id}/edit:- * patch:- * summary: Edit an existing resource- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: ID of the resource to edit-- * tags:- * - resources- * responses:- * 201:- * description: OK, resource edited successfuly- * 400:- * description: Bad request. Resource body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */-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({- where: { id: safeQuery.data.id },- data: safeBody.data,- });- const data = schemaResourcePublic.parse(resource);-- if (data) res.status(200).json({ data });- else- (error: Error) =>- res.status(404).json({- message: `Event type with ID ${safeQuery.data.id} not found and wasn't updated`,- error,- });-}--export default withMiddleware("HTTP_PATCH")(- withValidQueryIdTransformParseInt(withValidResource(editResource))-);diff --git a/templates/endpoints/[id]/index.ts b/templates/endpoints/[id]/index.tsdeleted file mode 100644index da3a2fd2dd2..00000000000--- a/templates/endpoints/[id]/index.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import type { ResourceResponse } from "@lib/types";-import { schemaResourcePublic } from "@lib/validations/resource";-import {- schemaQueryIdParseInt,- withValidQueryIdTransformParseInt,-} from "@lib/validations/shared/queryIdTransformParseInt";--/**- * @swagger- * /v1/resources/{id}:- * get:- * summary: Find a resource- * parameters:- * - in: path- * name: id- * schema:- * type: integer- * required: true- * description: ID of the resource to get-- * tags:- * - resources- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: Resource was not found- */-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 } });- const data = schemaResourcePublic.parse(resource);-- if (resource) res.status(200).json({ data });- else- (error: Error) =>- res.status(404).json({- message: "Resource was not found",- error,- });-}--export default withMiddleware("HTTP_GET")(withValidQueryIdTransformParseInt(resourceById));diff --git a/templates/endpoints/get_all.ts b/templates/endpoints/get_all.tsdeleted file mode 100644index e925133346e..00000000000--- a/templates/endpoints/get_all.ts+++ /dev/null@@ -1,38 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import { ResourcesResponse } from "@lib/types";-import { schemaResourcePublic } from "@lib/validations/resource";--/**- * @swagger- * /v1/resources:- * get:- * summary: Find all resources-- * tags:- * - resources- * responses:- * 200:- * description: OK- * 401:- * description: Authorization information is missing or invalid.- * 404:- * description: No resources were found- */-async function allResources(_: NextApiRequest, res: NextApiResponse<ResourcesResponse>) {- const resources = await prisma.resource.findMany();- const data = resources.map((resource) => schemaResourcePublic.parse(resource));-- if (data) res.status(200).json({ data });- else- (error: Error) =>- res.status(404).json({- message: "No Resources were found",- error,- });-}--export default withMiddleware("HTTP_GET")(allResources);diff --git a/templates/endpoints/get_all_and_post.ts b/templates/endpoints/get_all_and_post.tsdeleted file mode 100644index d1cc4ea665a..00000000000--- a/templates/endpoints/get_all_and_post.ts+++ /dev/null@@ -1,75 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--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:- * get:- * summary: Find all payments-- * tags:- * - payments- * responses:- * 200:- * description: OK- * 401:- * 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-- * tags:- * - payments- * responses:- * 201:- * description: OK, payment created- * 400:- * description: Bad request. Payment body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */- const safe = schemaPaymentBodyParams.safeParse(body);- if (!safe.success) {- res.status(400).json({ message: "Invalid request body" });- return;- }-- const payment = await prisma.payment.create({ data: safe.data });- const data = schemaPaymentPublic.parse(payment);-- if (data) res.status(201).json({ data, message: "Payment created successfully" });- else- (error: Error) =>- res.status(400).json({- message: "Could not create new payment",- error,- });- } else res.status(405).json({ message: `Method ${method} not allowed` });-}--export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllPayments);diff --git a/templates/endpoints/post.ts b/templates/endpoints/post.tsdeleted file mode 100644index 2b91522c62e..00000000000--- a/templates/endpoints/post.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import prisma from "@calcom/prisma";--import { withMiddleware } from "@lib/helpers/withMiddleware";-import type { ResourceResponse } from "@lib/types";-import { schemaResourceBodyParams, schemaResourcePublic, withValidResource } from "@lib/validations/resource";--/**- * @swagger- * /v1/resources/new:- * post:- * summary: Creates a new resource- * requestBody:- * description: Optional description in *Markdown*- * required: true- * content:- * application/json:- * schema:- * $ref: '#/components/schemas/Resource'-- * tags:- * - resources- * responses:- * 201:- * description: OK, resource created- * 400:- * description: Bad request. Resource body is invalid.- * 401:- * description: Authorization information is missing or invalid.- */-async function createResource({ body }: NextApiRequest, res: NextApiResponse<ResourceResponse>) {- const safe = schemaResourceBodyParams.safeParse(body);- if (!safe.success) {- res.status(400).json({ message: "Invalid request body" });- return;- }-- const resource = await prisma.resource.create({ data: safe.data });- const data = schemaResourcePublic.parse(resource);-- if (data) res.status(201).json({ data, message: "Resource created successfully" });- else- (error: Error) =>- res.status(400).json({- message: "Could not create new resource",- error,- });-}--export default withMiddleware("HTTP_POST")(withValidResource(createResource));diff --git a/templates/zod-validation.ts b/templates/zod-validation.tsdeleted file mode 100644index 82a95a97d10..00000000000--- a/templates/zod-validation.ts+++ /dev/null@@ -1,16 +0,0 @@-import { z } from "zod";--import { _ModelModel as Model } from "@calcom/prisma/zod";--export const schemaModelBaseBodyParams = Model.omit({ id: true, userId: true, createdAt: true }).partial();--const schemaModelRequiredParams = z.object({- email: z.string().email(),-});--export const schemaModelBodyParams = schemaModelBaseBodyParams.merge(schemaModelRequiredParams);--export const schemaModelPublic = Model.omit({- id: true,- userId: true,-});