Merge pull request #132 from calcom/fix/userId-not-id

fix: userId not, id remove templates stall
This commit is contained in:
Agusti Fernandez Pardo authored and GitHub committed 2022-06-24 00:12:10 +02:00
commit 9b142640d5
17 files changed
+17 -403

No files matched your search

+2 -4
View File
@@ -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: {
+5
View File
@@ -13,3 +13,8 @@ export const schemaQueryUserId = baseApiParams
.transform((id) => parseInt(id)),
})
.strict();
export const withValidQueryUserId = withValidation({
schema: schemaQueryUserId,
type: "Zod",
mode: "query",
});
+1 -1
View File
@@ -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) =>
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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"),
-1
View File
@@ -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";
+2 -2
View File
@@ -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" });
-49
View File
@@ -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.
-50
View File
@@ -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));
-58
View File
@@ -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))
);
-52
View File
@@ -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));
-38
View File
@@ -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);
-75
View File
@@ -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);
-51
View File
@@ -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));
-16
View File
@@ -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,
});