From 04b9b71310f29ef93fc8c03ed1a47941c9066e20 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Fri, 24 Jun 2022 00:09:23 +0200 Subject: [PATCH] fix: userId not, id remove templates stall --- lib/utils/webhookSubscriptions.ts | 6 +- lib/validations/shared/queryUserId.ts | 5 ++ pages/api/bookings/index.ts | 2 +- pages/api/users/[userId]/_delete.ts | 2 +- pages/api/users/[userId]/_get.ts | 3 +- pages/api/users/[userId]/_patch.ts | 2 +- pages/api/users/[userId]/index.ts | 6 +- pages/api/users/_get.ts | 1 - pages/api/users/_post.ts | 4 +- templates/README.md | 49 ---------------- templates/endpoints/[id]/delete.ts | 50 ----------------- templates/endpoints/[id]/edit.ts | 58 ------------------- templates/endpoints/[id]/index.ts | 52 ----------------- templates/endpoints/get_all.ts | 38 ------------- templates/endpoints/get_all_and_post.ts | 75 ------------------------- templates/endpoints/post.ts | 51 ----------------- templates/zod-validation.ts | 16 ------ 17 files changed, 17 insertions(+), 403 deletions(-) delete mode 100644 templates/README.md delete mode 100644 templates/endpoints/[id]/delete.ts delete mode 100644 templates/endpoints/[id]/edit.ts delete mode 100644 templates/endpoints/[id]/index.ts delete mode 100644 templates/endpoints/get_all.ts delete mode 100644 templates/endpoints/get_all_and_post.ts delete mode 100644 templates/endpoints/post.ts delete mode 100644 templates/zod-validation.ts diff --git a/lib/utils/webhookSubscriptions.ts b/lib/utils/webhookSubscriptions.ts index e53b15e7c5..af185248b3 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.ts index cbe6e282d2..94a7700003 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.ts index fb1fd347aa..b70e059d8b 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.ts index ac15975931..0f5c208e2a 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 user diff --git a/pages/api/users/[userId]/_get.ts b/pages/api/users/[userId]/_get.ts index 2fda8ddc91..76b2603a89 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 user diff --git a/pages/api/users/[userId]/_patch.ts b/pages/api/users/[userId]/_patch.ts index 58efa5773b..b7bf27c47f 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 user diff --git a/pages/api/users/[userId]/index.ts b/pages/api/users/[userId]/index.ts index 7d8887e5d1..66c0e9b25c 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.ts index 7f90ba8a27..42ec41ecfb 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.ts index 2217c49127..8809aa7e8a 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.md deleted file mode 100644 index 3a171b9318..0000000000 --- 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.ts deleted file mode 100644 index 39e026f418..0000000000 --- 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) { - 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.ts deleted file mode 100644 index cb4b1f05c5..0000000000 --- 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) { - 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.ts deleted file mode 100644 index da3a2fd2dd..0000000000 --- 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) { - 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.ts deleted file mode 100644 index e925133346..0000000000 --- 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) { - 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.ts deleted file mode 100644 index d1cc4ea665..0000000000 --- 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 -) { - 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.ts deleted file mode 100644 index 2b91522c62..0000000000 --- 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) { - 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.ts deleted file mode 100644 index 82a95a97d1..0000000000 --- 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, -});