From c2234593dbafb7d846fa49cd909ddfad3373b563 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Fri, 25 Mar 2022 19:37:51 +0100 Subject: [PATCH 1/3] feat: adds module transpiling so api can require @calcom/prisma and not @prisma/client directly --- README.md | 3 +++ lib/validations/apiKey.ts | 16 +++++++++++++ next.config.js | 9 ++++++-- package.json | 3 ++- pages/api/api-keys/[id]/delete.ts | 36 ++++++++++++++++++++++++++++++ pages/api/api-keys/[id]/edit.ts | 37 +++++++++++++++++++++++++++++++ pages/api/api-keys/[id]/index.ts | 31 ++++++++++++++++++++++++++ pages/api/api-keys/index.ts | 19 ++++++++++++++++ pages/api/api-keys/new.ts | 30 +++++++++++++++++++++++++ tsconfig.json | 2 ++ 10 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 lib/validations/apiKey.ts create mode 100644 pages/api/api-keys/[id]/delete.ts create mode 100644 pages/api/api-keys/[id]/edit.ts create mode 100644 pages/api/api-keys/[id]/index.ts create mode 100644 pages/api/api-keys/index.ts create mode 100644 pages/api/api-keys/new.ts diff --git a/README.md b/README.md index c2320f50c9..f8834ae82d 100644 --- a/README.md +++ b/README.md @@ -39,3 +39,6 @@ We aim to provide a fully tested API for our peace of mind, this is accomplished Since this will only support an API, we redirect the requests to root to the /api folder. We also added a redirect for future-proofing API versioning when we might need it, without having to resort to dirty hacks like a v1/v2 folders with lots of duplicated code, instead we redirect /api/v*/:rest to /api/:rest?version=* + + +The priority is the booking-related API routes so people can build their own booking flow, then event type management routes, then availability management routes etc \ No newline at end of file diff --git a/lib/validations/apiKey.ts b/lib/validations/apiKey.ts new file mode 100644 index 0000000000..5ed6e12b76 --- /dev/null +++ b/lib/validations/apiKey.ts @@ -0,0 +1,16 @@ +import { withValidation } from "next-validations"; +import { z } from "zod"; + +const schemaApiKey = z + .object({ + expiresAt: z.date().optional(), // default is 30 days + note: z.string().min(1).optional(), + }) + .strict(); // Adding strict so that we can disallow passing in extra fields +const withValidApiKey = withValidation({ + schema: schemaApiKey, + type: "Zod", + mode: "body", +}); + +export { schemaApiKey, withValidApiKey }; diff --git a/next.config.js b/next.config.js index 1e6d5beae6..3f24426e89 100644 --- a/next.config.js +++ b/next.config.js @@ -1,4 +1,9 @@ -module.exports = { +const withTM = require("next-transpile-modules")([ + "@calcom/prisma", +]); + + +module.exports = withTM({ async rewrites() { return [ // This redirects requests recieved at / the root to the /api/ folder. @@ -13,4 +18,4 @@ module.exports = { }, ]; }, -}; +}); diff --git a/package.json b/package.json index 12a5753dc7..f829c22786 100644 --- a/package.json +++ b/package.json @@ -31,9 +31,10 @@ "node-mocks-http": "^1.11.0" }, "dependencies": { - "typescript": "^4.6.3", "next": "^12.1.0", + "next-transpile-modules": "^9.0.0", "next-validations": "^0.1.11", + "typescript": "^4.6.3", "zod": "^3.14.2" } } diff --git a/pages/api/api-keys/[id]/delete.ts b/pages/api/api-keys/[id]/delete.ts new file mode 100644 index 0000000000..7912907b51 --- /dev/null +++ b/pages/api/api-keys/[id]/delete.ts @@ -0,0 +1,36 @@ +import { PrismaClient } from "@prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; + +const prisma = new PrismaClient(); + +type ResponseData = { + message?: string; + error?: unknown; +}; + +export async function eventType(req: NextApiRequest, res: NextApiResponse) { + const { query, method } = req; + const safe = await schemaQueryId.safeParse(query); + if (safe.success) { + if (method === "DELETE") { + // DELETE WILL DELETE THE EVENT TYPE + prisma.eventType + .delete({ where: { id: safe.data.id } }) + .then(() => { + // We only remove the event type from the database if there's an existing resource. + res.status(200).json({ message: `event-type with id: ${safe.data.id} deleted successfully` }); + }) + .catch((error) => { + // This catches the error thrown by prisma.eventType.delete() if the resource is not found. + res.status(400).json({ message: `Resource with id:${safe.data.id} was not found`, error: error }); + }); + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only DELETE Method allowed in /event-types/[id]/delete endpoint" }); + } + } +} + +export default withValidQueryId(eventType); diff --git a/pages/api/api-keys/[id]/edit.ts b/pages/api/api-keys/[id]/edit.ts new file mode 100644 index 0000000000..c4eac80975 --- /dev/null +++ b/pages/api/api-keys/[id]/edit.ts @@ -0,0 +1,37 @@ +import { PrismaClient, EventType } from "@prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaEventType, withValidEventType } from "@lib/validations/eventType"; +import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; + +const prisma = new PrismaClient(); + +type ResponseData = { + data?: EventType; + message?: string; + error?: unknown; +}; + +export async function editEventType(req: NextApiRequest, res: NextApiResponse) { + const { query, body, method } = req; + const safeQuery = await schemaQueryId.safeParse(query); + const safeBody = await schemaEventType.safeParse(body); + + if (method === "PATCH") { + if (safeQuery.success && safeBody.success) { + await prisma.eventType.update({ + where: { id: safeQuery.data.id }, + data: safeBody.data, + }).then(event => { + res.status(200).json({ data: event }); + }).catch(error => { + res.status(404).json({ message: `Event type with ID ${safeQuery.data.id} not found and wasn't updated`, error }) + }); + } + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only PATCH Method allowed for updating event-types" }); + } +} + +export default withValidQueryId(withValidEventType(editEventType)); diff --git a/pages/api/api-keys/[id]/index.ts b/pages/api/api-keys/[id]/index.ts new file mode 100644 index 0000000000..087a30cd55 --- /dev/null +++ b/pages/api/api-keys/[id]/index.ts @@ -0,0 +1,31 @@ +import { PrismaClient, EventType } from "@prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; + +const prisma = new PrismaClient(); + +type ResponseData = { + data?: EventType; + message?: string; + error?: unknown; +}; + +export async function eventType(req: NextApiRequest, res: NextApiResponse) { + const { query, method } = req; + const safe = await schemaQueryId.safeParse(query); + if (safe.success) { + if (method === "GET") { + const event = await prisma.eventType.findUnique({ where: { id: safe.data.id } }); + + if (event) res.status(200).json({ data: event }); + if (!event) res.status(404).json({ message: "Event type not found" }); + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only GET Method allowed" }); + } + } +} + + +export default withValidQueryId(eventType); diff --git a/pages/api/api-keys/index.ts b/pages/api/api-keys/index.ts new file mode 100644 index 0000000000..257fa060a1 --- /dev/null +++ b/pages/api/api-keys/index.ts @@ -0,0 +1,19 @@ +import { PrismaClient, ApiKey } from "@prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +const prisma = new PrismaClient(); +type ResponseData = { + data?: ApiKey[]; + error?: unknown; +}; + +export default async function apiKey(req: NextApiRequest, res: NextApiResponse) { + try { + const apiKeys = await prisma.apiKey.findMany({ where: { id: `${req.query.eventTypeId}` } }); + res.status(200).json({ data: { ...apiKeys } }); + } catch (error) { + console.log(error); + // FIXME: Add zod for validation/error handling + res.status(400).json({ error: error }); + } +} diff --git a/pages/api/api-keys/new.ts b/pages/api/api-keys/new.ts new file mode 100644 index 0000000000..5c4e210cca --- /dev/null +++ b/pages/api/api-keys/new.ts @@ -0,0 +1,30 @@ +import { PrismaClient, ApiKey } from "@prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaApiKey, withValidApiKey } from "@lib/validations/apiKey"; + +const prisma = new PrismaClient(); +type ResponseData = { + data?: ApiKey; + message?: string; + error?: string; +}; + +async function createApiKey(req: NextApiRequest, res: NextApiResponse) { + const { body, method } = req; + if (method === "POST") { + const safe = schemaApiKey.safeParse(body); + if (safe.success && safe.data) { + await prisma.apiKey + .create({ data: { ...safe.data, user: { connect: { id: 1 } } +}}) + .then((event) => res.status(201).json({ data: event })) + .catch((error) => res.status(400).json({ message: "Could not create event type", error: error })); + } + } else { + // Reject any other HTTP method than POST + res.status(405).json({ error: "Only POST Method allowed" }); + } +} + +export default withValidApiKey(createApiKey); diff --git a/tsconfig.json b/tsconfig.json index b9b2164ce0..951cbeb88c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,7 +21,9 @@ "jsx": "preserve", "paths": { "@api/*": ["pages/api/*"], + "@prisma/client/*": ["@calcom/prisma/client/*"], "@lib/*": ["lib/*"] + }, }, "include": [ From d9c34f67e628a8af413d7f9b0785082018cadfe7 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Fri, 25 Mar 2022 20:17:37 +0100 Subject: [PATCH 2/3] feat: adds api keys endpoints, new QueryIdAsString as apiKey has a UUID string-like ID unlike the numbers of event-type or others --- lib/validations/queryIdString.ts | 20 ++++++++++++++++ lib/validations/queryIdTransformParseInt.ts | 4 ++-- next.config.js | 3 +++ pages/api/api-keys/[id]/delete.ts | 22 ++++++++--------- pages/api/api-keys/[id]/edit.ts | 26 ++++++++++----------- pages/api/api-keys/[id]/index.ts | 20 ++++++++-------- pages/api/api-keys/index.ts | 6 ++--- pages/api/api-keys/new.ts | 10 ++++---- pages/api/event-types/[id]/delete.ts | 8 +++---- pages/api/event-types/[id]/edit.ts | 10 ++++---- pages/api/event-types/[id]/index.ts | 10 ++++---- pages/api/event-types/index.ts | 6 ++--- pages/api/event-types/new.ts | 6 ++--- 13 files changed, 86 insertions(+), 65 deletions(-) create mode 100644 lib/validations/queryIdString.ts diff --git a/lib/validations/queryIdString.ts b/lib/validations/queryIdString.ts new file mode 100644 index 0000000000..02c1e6aee5 --- /dev/null +++ b/lib/validations/queryIdString.ts @@ -0,0 +1,20 @@ +import { withValidation } from "next-validations"; +import { z } from "zod"; + +// Extracted out as utility function so can be reused +// at different endpoints that require this validation. +const schemaQueryId = z + .object({ + // since nextjs parses query params as strings, + // we need to cast them to numbers using z.transform() and parseInt() + id: z.string().uuid() + }) + .strict(); + +const withValidQueryIdString = withValidation({ + schema: schemaQueryId, + type: "Zod", + mode: "query", +}); + +export { schemaQueryId, withValidQueryIdString }; diff --git a/lib/validations/queryIdTransformParseInt.ts b/lib/validations/queryIdTransformParseInt.ts index 1bbb5cfa09..f99ea64e18 100644 --- a/lib/validations/queryIdTransformParseInt.ts +++ b/lib/validations/queryIdTransformParseInt.ts @@ -14,10 +14,10 @@ const schemaQueryId = z }) .strict(); -const withValidQueryId = withValidation({ +const withValidQueryIdTransformParseInt = withValidation({ schema: schemaQueryId, type: "Zod", mode: "query", }); -export { schemaQueryId, withValidQueryId }; +export { schemaQueryId, withValidQueryIdTransformParseInt }; diff --git a/next.config.js b/next.config.js index 3f24426e89..7cd0ff53d7 100644 --- a/next.config.js +++ b/next.config.js @@ -1,7 +1,10 @@ +// https://www.npmjs.com/package/next-transpile-modules +// This makes our @calcom/prisma package from the monorepo to be transpiled and usable by API const withTM = require("next-transpile-modules")([ "@calcom/prisma", ]); +// use something like withPlugins([withTM], {}) if more plugins added later. module.exports = withTM({ async rewrites() { diff --git a/pages/api/api-keys/[id]/delete.ts b/pages/api/api-keys/[id]/delete.ts index 7912907b51..488712d91d 100644 --- a/pages/api/api-keys/[id]/delete.ts +++ b/pages/api/api-keys/[id]/delete.ts @@ -1,36 +1,34 @@ -import { PrismaClient } from "@prisma/client"; -import type { NextApiRequest, NextApiResponse } from "next"; +import prisma from "@calcom/prisma"; +import { NextApiRequest, NextApiResponse } from "next"; -import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; - -const prisma = new PrismaClient(); +import { schemaQueryId, withValidQueryIdString } from "@lib/validations/queryIdString"; type ResponseData = { message?: string; error?: unknown; }; -export async function eventType(req: NextApiRequest, res: NextApiResponse) { +export async function apiKey(req: NextApiRequest, res: NextApiResponse) { const { query, method } = req; const safe = await schemaQueryId.safeParse(query); if (safe.success) { if (method === "DELETE") { // DELETE WILL DELETE THE EVENT TYPE - prisma.eventType + prisma.apiKey .delete({ where: { id: safe.data.id } }) .then(() => { - // We only remove the event type from the database if there's an existing resource. - res.status(200).json({ message: `event-type with id: ${safe.data.id} deleted successfully` }); + // We only remove the api key from the database if there's an existing resource. + res.status(200).json({ message: `api-key with id: ${safe.data.id} deleted successfully` }); }) .catch((error) => { - // This catches the error thrown by prisma.eventType.delete() if the resource is not found. + // This catches the error thrown by prisma.apiKey.delete() if the resource is not found. res.status(400).json({ message: `Resource with id:${safe.data.id} was not found`, error: error }); }); } else { // Reject any other HTTP method than POST - res.status(405).json({ message: "Only DELETE Method allowed in /event-types/[id]/delete endpoint" }); + res.status(405).json({ message: "Only DELETE Method allowed in /api-keys/[id]/delete endpoint" }); } } } -export default withValidQueryId(eventType); +export default withValidQueryIdString(apiKey); diff --git a/pages/api/api-keys/[id]/edit.ts b/pages/api/api-keys/[id]/edit.ts index c4eac80975..ce97a24b8e 100644 --- a/pages/api/api-keys/[id]/edit.ts +++ b/pages/api/api-keys/[id]/edit.ts @@ -1,37 +1,37 @@ -import { PrismaClient, EventType } from "@prisma/client"; +import prisma from "@calcom/prisma"; + +import { ApiKey } from "@calcom/prisma/client"; import type { NextApiRequest, NextApiResponse } from "next"; -import { schemaEventType, withValidEventType } from "@lib/validations/eventType"; -import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; - -const prisma = new PrismaClient(); +import { schemaApiKey, withValidApiKey } from "@lib/validations/apiKey"; +import { schemaQueryId, withValidQueryIdString } from "@lib/validations/queryIdString"; type ResponseData = { - data?: EventType; + data?: ApiKey; message?: string; error?: unknown; }; -export async function editEventType(req: NextApiRequest, res: NextApiResponse) { +export async function editApiKey(req: NextApiRequest, res: NextApiResponse) { const { query, body, method } = req; const safeQuery = await schemaQueryId.safeParse(query); - const safeBody = await schemaEventType.safeParse(body); + const safeBody = await schemaApiKey.safeParse(body); if (method === "PATCH") { if (safeQuery.success && safeBody.success) { - await prisma.eventType.update({ + await prisma.apiKey.update({ where: { id: safeQuery.data.id }, data: safeBody.data, - }).then(event => { - res.status(200).json({ data: event }); + }).then(apiKey => { + res.status(200).json({ data: apiKey }); }).catch(error => { res.status(404).json({ message: `Event type with ID ${safeQuery.data.id} not found and wasn't updated`, error }) }); } } else { // Reject any other HTTP method than POST - res.status(405).json({ message: "Only PATCH Method allowed for updating event-types" }); + res.status(405).json({ message: "Only PATCH Method allowed for updating apiKey-types" }); } } -export default withValidQueryId(withValidEventType(editEventType)); +export default withValidQueryIdString(withValidApiKey(editApiKey)); diff --git a/pages/api/api-keys/[id]/index.ts b/pages/api/api-keys/[id]/index.ts index 087a30cd55..177ba289d9 100644 --- a/pages/api/api-keys/[id]/index.ts +++ b/pages/api/api-keys/[id]/index.ts @@ -1,25 +1,25 @@ -import { PrismaClient, EventType } from "@prisma/client"; +import prisma from "@calcom/prisma"; + +import { ApiKey } from "@calcom/prisma/client"; import type { NextApiRequest, NextApiResponse } from "next"; -import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; - -const prisma = new PrismaClient(); +import { schemaQueryId, withValidQueryIdString } from "@lib/validations/queryIdString"; type ResponseData = { - data?: EventType; + data?: ApiKey; message?: string; error?: unknown; }; -export async function eventType(req: NextApiRequest, res: NextApiResponse) { +export async function apiKey(req: NextApiRequest, res: NextApiResponse) { const { query, method } = req; const safe = await schemaQueryId.safeParse(query); if (safe.success) { if (method === "GET") { - const event = await prisma.eventType.findUnique({ where: { id: safe.data.id } }); + const apiKey = await prisma.apiKey.findUnique({ where: { id: safe.data.id } }); - if (event) res.status(200).json({ data: event }); - if (!event) res.status(404).json({ message: "Event type not found" }); + if (apiKey) res.status(200).json({ data: apiKey }); + if (!apiKey) res.status(404).json({ message: "Event type not found" }); } else { // Reject any other HTTP method than POST res.status(405).json({ message: "Only GET Method allowed" }); @@ -28,4 +28,4 @@ export async function eventType(req: NextApiRequest, res: NextApiResponse res.status(201).json({ data: event })) - .catch((error) => res.status(400).json({ message: "Could not create event type", error: error })); + .then((apiKey) => res.status(201).json({ data: apiKey })) + .catch((error) => res.status(400).json({ message: "Could not create apiKey", error: error })); } } else { // Reject any other HTTP method than POST diff --git a/pages/api/event-types/[id]/delete.ts b/pages/api/event-types/[id]/delete.ts index 7912907b51..52f2cd74b7 100644 --- a/pages/api/event-types/[id]/delete.ts +++ b/pages/api/event-types/[id]/delete.ts @@ -1,9 +1,9 @@ -import { PrismaClient } from "@prisma/client"; +import prisma from "@calcom/prisma"; + import type { NextApiRequest, NextApiResponse } from "next"; -import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt"; +import { schemaQueryId, withValidQueryIdTransformParseInt } from "@lib/validations/queryIdTransformParseInt"; -const prisma = new PrismaClient(); type ResponseData = { message?: string; @@ -33,4 +33,4 @@ export async function eventType(req: NextApiRequest, res: NextApiResponse Date: Fri, 25 Mar 2022 23:26:22 +0100 Subject: [PATCH 3/3] feat: improve api key endpoints, add users endpoint --- lib/validations/apiKey.ts | 2 +- lib/validations/queryIdString.ts | 2 +- lib/validations/user.ts | 62 ++++++++++++++++++++++++++++++++ pages/api/api-keys/index.ts | 2 +- pages/api/api-keys/new.ts | 13 +++++-- pages/api/event-types/index.ts | 2 +- pages/api/users/[id]/delete.ts | 36 +++++++++++++++++++ pages/api/users/[id]/edit.ts | 37 +++++++++++++++++++ pages/api/users/[id]/index.ts | 31 ++++++++++++++++ pages/api/users/index.ts | 19 ++++++++++ pages/api/users/new.ts | 29 +++++++++++++++ 11 files changed, 228 insertions(+), 7 deletions(-) create mode 100644 lib/validations/user.ts create mode 100644 pages/api/users/[id]/delete.ts create mode 100644 pages/api/users/[id]/edit.ts create mode 100644 pages/api/users/[id]/index.ts create mode 100644 pages/api/users/index.ts create mode 100644 pages/api/users/new.ts diff --git a/lib/validations/apiKey.ts b/lib/validations/apiKey.ts index 5ed6e12b76..ea0fbaec3a 100644 --- a/lib/validations/apiKey.ts +++ b/lib/validations/apiKey.ts @@ -3,7 +3,7 @@ import { z } from "zod"; const schemaApiKey = z .object({ - expiresAt: z.date().optional(), // default is 30 days + expiresAt: z.string().transform((date: string) => new Date(date)).optional(), // default is 30 days note: z.string().min(1).optional(), }) .strict(); // Adding strict so that we can disallow passing in extra fields diff --git a/lib/validations/queryIdString.ts b/lib/validations/queryIdString.ts index 02c1e6aee5..ef000f2014 100644 --- a/lib/validations/queryIdString.ts +++ b/lib/validations/queryIdString.ts @@ -7,7 +7,7 @@ const schemaQueryId = z .object({ // since nextjs parses query params as strings, // we need to cast them to numbers using z.transform() and parseInt() - id: z.string().uuid() + id: z.string() }) .strict(); diff --git a/lib/validations/user.ts b/lib/validations/user.ts new file mode 100644 index 0000000000..4b24b168af --- /dev/null +++ b/lib/validations/user.ts @@ -0,0 +1,62 @@ +import { withValidation } from "next-validations"; +import { schemaEventType } from "./eventType"; +// import { schemaCredential } from "./credential"; +// import { schemaMembership } from "./membership"; +// import { schemaBooking } from "./booking"; +// import { schemaSchedule } from "./schedule"; +// import { schemaSelectedCalendar } from "./selectedCalendar"; +// import { schemaAvailability } from "./availability"; +// import { schemaWebhook } from "./webhook"; + +import { z } from "zod"; +import { schemaApiKey } from "./apiKey"; + +const schemaUser = z + .object({ + username: z.string().min(3), + name: z.string().min(3), + email: z.string().email(), // max is a full day. + emailVerified: z.date().optional(), + password: z.string().optional(), + bio: z.string().min(3).optional(), + avatar: z.string().optional(), + timeZone: z.string().default("Europe/London"), + weekStart: z.string().default("Sunday"), + bufferTime: z.number().default(0), + hideBranding: z.boolean().default(false), + theme: z.string().optional(), + trialEndsAt: z.date().optional(), + eventTypes: z.array((schemaEventType)).optional(), + // credentials: z.array((schemaCredentials)).optional(), + // teams: z.array((schemaMembership)).optional(), + // bookings: z.array((schemaBooking)).optional(), + // schedules: z.array((schemaSchedule)).optional(), + defaultScheduleId: z.number().optional(), + // selectedCalendars: z.array((schemaSelectedCalendar)).optional(), + completedOnboarding: z.boolean().default(false), + locale: z.string().optional(), + timeFormat: z.number().optional().default(12), + twoFactorEnabled: z.boolean().default(false), + twoFactorSecret: z.string().optional(), + identityProvider: z.enum(["CAL", "SAML", "GOOGLE"]).optional().default("CAL"), + identityProviderId: z.string().optional(), + // availavility: z.array((schemaAvailavility)).optional(), + invitedTo: z.number().optional(), + plan: z.enum(['FREE', 'TRIAL', 'PRO']).default("TRIAL"), + // webhooks: z.array((schemaWebhook)).optional(), + brandColor: z.string().default("#292929"), + darkBrandColor: z.string().default("#fafafa"), + // destinationCalendar: z.instanceof(schemaEventType).optional(), // FIXME: instanceof doesnt work here + away: z.boolean().default(false), + metadata: z.object({}).optional(), + verified: z.boolean().default(false), + apiKeys: z.array((schemaApiKey)).optional(), + }) + .strict(); // Adding strict so that we can disallow passing in extra fields +const withValidUser = withValidation({ + schema: schemaUser, + type: "Zod", + mode: "body", +}); + +export { schemaUser, withValidUser }; diff --git a/pages/api/api-keys/index.ts b/pages/api/api-keys/index.ts index d6337207e2..ed0314a9fc 100644 --- a/pages/api/api-keys/index.ts +++ b/pages/api/api-keys/index.ts @@ -9,7 +9,7 @@ type ResponseData = { export default async function apiKey(req: NextApiRequest, res: NextApiResponse) { try { - const apiKeys = await prisma.apiKey.findMany({ where: { id: `${req.query.eventTypeId}` } }); + const apiKeys = await prisma.apiKey.findMany({}); res.status(200).json({ data: { ...apiKeys } }); } catch (error) { console.log(error); diff --git a/pages/api/api-keys/new.ts b/pages/api/api-keys/new.ts index 2e649321c0..4133ea80c2 100644 --- a/pages/api/api-keys/new.ts +++ b/pages/api/api-keys/new.ts @@ -16,10 +16,17 @@ async function createApiKey(req: NextApiRequest, res: NextApiResponse res.status(201).json({ data: apiKey })) - .catch((error) => res.status(400).json({ message: "Could not create apiKey", error: error })); + .catch((error) => { + console.log(error); + res.status(400).json({ message: "Could not create apiKey", error: error }) + } + ) } } else { // Reject any other HTTP method than POST diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.ts index faad9e43ba..491989884f 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -9,7 +9,7 @@ type ResponseData = { export default async function eventType(req: NextApiRequest, res: NextApiResponse) { try { - const eventTypes = await prisma.eventType.findMany({ where: { id: Number(req.query.eventTypeId) } }); + const eventTypes = await prisma.eventType.findMany(); res.status(200).json({ data: { ...eventTypes } }); } catch (error) { console.log(error); diff --git a/pages/api/users/[id]/delete.ts b/pages/api/users/[id]/delete.ts new file mode 100644 index 0000000000..3c35fd5844 --- /dev/null +++ b/pages/api/users/[id]/delete.ts @@ -0,0 +1,36 @@ +import prisma from "@calcom/prisma"; + +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaQueryId, withValidQueryIdTransformParseInt } from "@lib/validations/queryIdTransformParseInt"; + + +type ResponseData = { + message?: string; + error?: unknown; +}; + +export async function user(req: NextApiRequest, res: NextApiResponse) { + const { query, method } = req; + const safe = await schemaQueryId.safeParse(query); + if (safe.success) { + if (method === "DELETE") { + // DELETE WILL DELETE THE EVENT TYPE + prisma.user + .delete({ where: { id: safe.data.id } }) + .then(() => { + // We only remove the user type from the database if there's an existing resource. + res.status(200).json({ message: `user-type with id: ${safe.data.id} deleted successfully` }); + }) + .catch((error) => { + // This catches the error thrown by prisma.user.delete() if the resource is not found. + res.status(400).json({ message: `Resource with id:${safe.data.id} was not found`, error: error }); + }); + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only DELETE Method allowed in /user-types/[id]/delete endpoint" }); + } + } +} + +export default withValidQueryIdTransformParseInt(user); diff --git a/pages/api/users/[id]/edit.ts b/pages/api/users/[id]/edit.ts new file mode 100644 index 0000000000..1332b3c686 --- /dev/null +++ b/pages/api/users/[id]/edit.ts @@ -0,0 +1,37 @@ +import prisma from "@calcom/prisma"; + +import { User } from "@calcom/prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaUser, withValidUser } from "@lib/validations/user"; +import { schemaQueryId, withValidQueryIdTransformParseInt } from "@lib/validations/queryIdTransformParseInt"; + +type ResponseData = { + data?: User; + message?: string; + error?: unknown; +}; + +export async function editUser(req: NextApiRequest, res: NextApiResponse) { + const { query, body, method } = req; + const safeQuery = await schemaQueryId.safeParse(query); + const safeBody = await schemaUser.safeParse(body); + + if (method === "PATCH") { + if (safeQuery.success && safeBody.success) { + await prisma.user.update({ + where: { id: safeQuery.data.id }, + data: safeBody.data, + }).then(user => { + res.status(200).json({ data: user }); + }).catch(error => { + res.status(404).json({ message: `Event type with ID ${safeQuery.data.id} not found and wasn't updated`, error }) + }); + } + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only PATCH Method allowed for updating user-types" }); + } +} + +export default withValidQueryIdTransformParseInt(withValidUser(editUser)); diff --git a/pages/api/users/[id]/index.ts b/pages/api/users/[id]/index.ts new file mode 100644 index 0000000000..7b6c991f2b --- /dev/null +++ b/pages/api/users/[id]/index.ts @@ -0,0 +1,31 @@ +import prisma from "@calcom/prisma"; + +import { User } from "@calcom/prisma/client"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaQueryId, withValidQueryIdTransformParseInt } from "@lib/validations/queryIdTransformParseInt"; + +type ResponseData = { + data?: User; + message?: string; + error?: unknown; +}; + +export async function user(req: NextApiRequest, res: NextApiResponse) { + const { query, method } = req; + const safe = await schemaQueryId.safeParse(query); + if (safe.success) { + if (method === "GET") { + const user = await prisma.user.findUnique({ where: { id: safe.data.id } }); + + if (user) res.status(200).json({ data: user }); + if (!user) res.status(404).json({ message: "Event type not found" }); + } else { + // Reject any other HTTP method than POST + res.status(405).json({ message: "Only GET Method allowed" }); + } + } +} + + +export default withValidQueryIdTransformParseInt(user); diff --git a/pages/api/users/index.ts b/pages/api/users/index.ts new file mode 100644 index 0000000000..3d03dcf205 --- /dev/null +++ b/pages/api/users/index.ts @@ -0,0 +1,19 @@ +import prisma from "@calcom/prisma"; + +import { User } from "@calcom/prisma/client";import type { NextApiRequest, NextApiResponse } from "next"; + +type ResponseData = { + data?: User[]; + error?: unknown; +}; + +export default async function user(req: NextApiRequest, res: NextApiResponse) { + try { + const users = await prisma.user.findMany(); + res.status(200).json({ data: { ...users } }); + } catch (error) { + console.log(error); + // FIXME: Add zod for validation/error handling + res.status(400).json({ error: error }); + } +} diff --git a/pages/api/users/new.ts b/pages/api/users/new.ts new file mode 100644 index 0000000000..4dee441ff5 --- /dev/null +++ b/pages/api/users/new.ts @@ -0,0 +1,29 @@ +import prisma from "@calcom/prisma"; + +import { User } from "@calcom/prisma/client";import type { NextApiRequest, NextApiResponse } from "next"; + +import { schemaUser, withValidUser } from "@lib/validations/user"; + +type ResponseData = { + data?: User; + message?: string; + error?: string; +}; + +async function createUser(req: NextApiRequest, res: NextApiResponse) { + const { body, method } = req; + if (method === "POST") { + const safe = schemaUser.safeParse(body); + if (safe.success && safe.data) { + await prisma.user + .create({ data: safe.data }) + .then((user) => res.status(201).json({ data: user })) + .catch((error) => res.status(400).json({ message: "Could not create user type", error: error })); + } + } else { + // Reject any other HTTP method than POST + res.status(405).json({ error: "Only POST Method allowed" }); + } +} + +export default withValidUser(createUser);