diff --git a/__tests__/api-keys/api-key.id.test.edit.ts b/__tests__/api-keys/api-key.id.test.edit.ts new file mode 100644 index 0000000000..0e0f5f88b8 --- /dev/null +++ b/__tests__/api-keys/api-key.id.test.edit.ts @@ -0,0 +1,92 @@ +import handleapiKeyEdit from "@api/api-keys/[id]/edit"; +import { createMocks } from "node-mocks-http"; + +import prisma from "@calcom/prisma"; +import {stringifyISODate} from "@lib/utils/stringifyISODate"; + +describe("PATCH /api/api-keys/[id]/edit with valid id and body updates an apiKey-type", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "PATCH", + query: { + id: "cl16zg6860000wwylnsgva00b", + }, + body: { + note: "Updated note", + }, + }); + const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id } }); + await handleapiKeyEdit(req, res); + + expect(res._getStatusCode()).toBe(200); + expect(JSON.parse(res._getData())).toEqual({ data: {...apiKey, createdAt: stringifyISODate(apiKey?.createdAt), expiresAt: stringifyISODate(apiKey?.expiresAt)} }); + }); +}); + +// describe("PATCH /api/api-keys/[id]/edit with invalid id returns 404", () => { +// it("returns a message with the specified apiKeys", async () => { +// const { req, res } = createMocks({ +// method: "PATCH", +// query: { +// id: "cl16zg6860000wwylnsgva00a", +// }, +// body: { +// note: "Updated note", +// }, +// }); +// const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id } }); +// await handleapiKeyEdit(req, res); + +// expect(res._getStatusCode()).toBe(404); +// if (apiKey) apiKey.note = "Updated note"; +// expect(JSON.parse(res._getData())).toStrictEqual({ "error": { +// "clientVersion": "3.10.0", +// "code": "P2025", +// "meta": { +// "cause": "Record to update not found.", +// }, +// }, +// "message": "apiKey with ID cl16zg6860000wwylnsgva00a not found and wasn't updated", }); +// }); +// }); + +describe("PATCH /api/api-keys/[id]/edit with valid id and no body returns 200 with an apiKey with no note and default expireAt", () => { + it("returns a message with the specified apiKeys", async () => { + const apiKey = await prisma.apiKey.create({data:{} }); + const { req, res } = createMocks({ + method: "PATCH", + query: { + id: apiKey?.id, + }, + }); + await handleapiKeyEdit(req, res); + + expect(apiKey?.note).toBeNull(); + expect(res._getStatusCode()).toBe(200); + expect(JSON.parse(res._getData())).toEqual({ data: {...apiKey, createdAt: stringifyISODate(apiKey?.createdAt), expiresAt: stringifyISODate(apiKey?.expiresAt)} }); + + }); +}); + +describe("POST /api/api-keys/[id]/edit fails, only PATCH allowed", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "POST", // This POST method is not allowed + query: { + id: "cl16zg6860000wwylnsgva00b", + }, + body: { + note: "Updated note", + }, + }); + await handleapiKeyEdit(req, res); + + expect(res._getStatusCode()).toBe(405); + expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only PATCH Method allowed for updating API keys" }); + }); +}); + +afterAll((done) => { + prisma.$disconnect().then(); + done(); +}); diff --git a/__tests__/api-keys/api-key.id.test.index.ts b/__tests__/api-keys/api-key.id.test.index.ts new file mode 100644 index 0000000000..010d034e1f --- /dev/null +++ b/__tests__/api-keys/api-key.id.test.index.ts @@ -0,0 +1,81 @@ +import handleApiKey from "@api/api-keys/[id]"; +import { createMocks } from "node-mocks-http"; + +import prisma from "@calcom/prisma"; +import {stringifyISODate} from "@lib/utils/stringifyISODate"; + +describe("GET /api/api-keys/[id] with valid id as string returns an apiKey", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "GET", + query: { + id: "cl16zg6860000wwylnsgva00b", + }, + }); + const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id} }); + await handleApiKey(req, res); + + expect(res._getStatusCode()).toBe(200); + expect(JSON.parse(res._getData())).toEqual({ data: {...apiKey, createdAt: stringifyISODate(apiKey?.createdAt), expiresAt: stringifyISODate(apiKey?.expiresAt)} }); + }); +}); + +// This can never happen under our normal nextjs setup where query is always a string | string[]. +// But seemed a good example for testing an error validation +describe("GET /api/api-keys/[id] errors if query id is number, requires a string", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "GET", + query: { + id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string + }, + }); + await handleApiKey(req, res); + + expect(res._getStatusCode()).toBe(400); + expect(JSON.parse(res._getData())).toStrictEqual([ + { + code: "invalid_type", + expected: "string", + received: "number", + path: ["id"], + message: "Expected string, received number", + }, + ]); + }); +}); + +describe("GET /api/api-keys/[id] an id not present in db like 0, throws 404 not found", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "GET", + query: { + id: "0", // There's no apiKey with id 0 + }, + }); + await handleApiKey(req, res); + + expect(res._getStatusCode()).toBe(404); + expect(JSON.parse(res._getData())).toStrictEqual({ message: "API key was not found" }); + }); +}); + +describe("POST /api/api-keys/[id] fails, only GET allowed", () => { + it("returns a message with the specified apiKeys", async () => { + const { req, res } = createMocks({ + method: "POST", // This POST method is not allowed + query: { + id: "1", + }, + }); + await handleApiKey(req, res); + + expect(res._getStatusCode()).toBe(405); + expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); + }); +}); + +afterAll((done) => { + prisma.$disconnect().then(); + done(); +}); diff --git a/__tests__/event-types/[id]/event-type.id.test.edit.ts b/__tests__/event-types/[id]/event-type.id.test.edit.ts index 8f55f76a53..ee9206298c 100644 --- a/__tests__/event-types/[id]/event-type.id.test.edit.ts +++ b/__tests__/event-types/[id]/event-type.id.test.edit.ts @@ -1,4 +1,4 @@ -import handleEventEdit from "@api/event-types/[id]/edit"; +import handleEventTypeEdit from "@api/event-types/[id]/edit"; import { createMocks } from "node-mocks-http"; import prisma from "@calcom/prisma"; @@ -16,8 +16,8 @@ describe("PATCH /api/event-types/[id]/edit with valid id and body updates an eve length: 1, }, }); - const event = await prisma.eventType.findUnique({ where: { id: 2 } }); - await handleEventEdit(req, res); + const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); + await handleEventTypeEdit(req, res); expect(res._getStatusCode()).toBe(200); if (event) event.title = "Updated title"; @@ -38,8 +38,8 @@ describe("PATCH /api/event-types/[id]/edit with invalid id returns 404", () => { length: 1, }, }); - const event = await prisma.eventType.findUnique({ where: { id: 2 } }); - await handleEventEdit(req, res); + const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); + await handleEventTypeEdit(req, res); expect(res._getStatusCode()).toBe(404); if (event) event.title = "Updated title"; @@ -62,7 +62,7 @@ describe("PATCH /api/event-types/[id]/edit with valid id and no body returns 400 id: "2", }, }); - await handleEventEdit(req, res); + await handleEventTypeEdit(req, res); expect(res._getStatusCode()).toBe(400); expect(JSON.parse(res._getData())).toStrictEqual([{"code": "invalid_type", "expected": "string", "message": "Required", "path": ["title"], "received": "undefined"}, {"code": "invalid_type", "expected": "string", "message": "Required", "path": ["slug"], "received": "undefined"}, {"code": "invalid_type", "expected": "number", "message": "Required", "path": ["length"], "received": "undefined"}]); @@ -82,7 +82,7 @@ describe("POST /api/event-types/[id]/edit fails, only PATCH allowed", () => { length: 1, }, }); - await handleEventEdit(req, res); + await handleEventTypeEdit(req, res); expect(res._getStatusCode()).toBe(405); expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only PATCH Method allowed for updating event-types" }); diff --git a/__tests__/event-types/[id]/event-type.id.test.index.ts b/__tests__/event-types/[id]/event-type.id.test.index.ts index a80e04c41c..61f7e718fe 100644 --- a/__tests__/event-types/[id]/event-type.id.test.index.ts +++ b/__tests__/event-types/[id]/event-type.id.test.index.ts @@ -1,4 +1,4 @@ -import handleEvent from "@api/event-types/[id]"; +import handleEventType from "@api/event-types/[id]"; import { createMocks } from "node-mocks-http"; import prisma from "@calcom/prisma"; @@ -12,7 +12,7 @@ describe("GET /api/event-types/[id] with valid id as string returns an event-typ }, }); const event = await prisma.eventType.findUnique({ where: { id: 1 } }); - await handleEvent(req, res); + await handleEventType(req, res); expect(res._getStatusCode()).toBe(200); expect(JSON.parse(res._getData())).toStrictEqual({ data: event }); @@ -29,7 +29,7 @@ describe("GET /api/event-types/[id] errors if query id is number, requires a str id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string }, }); - await handleEvent(req, res); + await handleEventType(req, res); expect(res._getStatusCode()).toBe(400); expect(JSON.parse(res._getData())).toStrictEqual([ @@ -52,7 +52,7 @@ describe("GET /api/event-types/[id] an id not present in db like 0, throws 404 n id: "0", // There's no event type with id 0 }, }); - await handleEvent(req, res); + await handleEventType(req, res); expect(res._getStatusCode()).toBe(404); expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" }); @@ -67,7 +67,7 @@ describe("POST /api/event-types/[id] fails, only GET allowed", () => { id: "1", }, }); - await handleEvent(req, res); + await handleEventType(req, res); expect(res._getStatusCode()).toBe(405); expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); diff --git a/lib/utils/stringifyISODate.ts b/lib/utils/stringifyISODate.ts new file mode 100644 index 0000000000..d01b174964 --- /dev/null +++ b/lib/utils/stringifyISODate.ts @@ -0,0 +1,3 @@ +export const stringifyISODate = (date: Date|undefined): string => { + return `${date?.toISOString()}` +} \ No newline at end of file diff --git a/lib/validations/apiKey.ts b/lib/validations/apiKey.ts index ea0fbaec3a..8b0069d974 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.string().transform((date: string) => new Date(date)).optional(), // default is 30 days + 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 diff --git a/lib/validations/queryIdString.ts b/lib/validations/queryIdString.ts index ef000f2014..c221606841 100644 --- a/lib/validations/queryIdString.ts +++ b/lib/validations/queryIdString.ts @@ -3,7 +3,7 @@ import { z } from "zod"; // Extracted out as utility function so can be reused // at different endpoints that require this validation. -const schemaQueryId = z +const schemaQueryIdAsString = z .object({ // since nextjs parses query params as strings, // we need to cast them to numbers using z.transform() and parseInt() @@ -12,9 +12,9 @@ const schemaQueryId = z .strict(); const withValidQueryIdString = withValidation({ - schema: schemaQueryId, + schema: schemaQueryIdAsString, type: "Zod", mode: "query", }); -export { schemaQueryId, withValidQueryIdString }; +export { schemaQueryIdAsString, withValidQueryIdString }; diff --git a/pages/api/api-keys/[id]/edit.ts b/pages/api/api-keys/[id]/edit.ts index ce97a24b8e..445cb429b4 100644 --- a/pages/api/api-keys/[id]/edit.ts +++ b/pages/api/api-keys/[id]/edit.ts @@ -1,10 +1,10 @@ import prisma from "@calcom/prisma"; -import { ApiKey } from "@calcom/prisma/client"; +import { ApiKey } from "@prisma/client"; import type { NextApiRequest, NextApiResponse } from "next"; import { schemaApiKey, withValidApiKey } from "@lib/validations/apiKey"; -import { schemaQueryId, withValidQueryIdString } from "@lib/validations/queryIdString"; +import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/queryIdString"; type ResponseData = { data?: ApiKey; @@ -14,7 +14,7 @@ type ResponseData = { export async function editApiKey(req: NextApiRequest, res: NextApiResponse) { const { query, body, method } = req; - const safeQuery = await schemaQueryId.safeParse(query); + const safeQuery = await schemaQueryIdAsString.safeParse(query); const safeBody = await schemaApiKey.safeParse(body); if (method === "PATCH") { @@ -25,12 +25,12 @@ export async function editApiKey(req: NextApiRequest, res: NextApiResponse { 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 }) + res.status(404).json({ message: `apiKey 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 apiKey-types" }); + res.status(405).json({ message: "Only PATCH Method allowed for updating API keys" }); } } diff --git a/pages/api/api-keys/[id]/index.ts b/pages/api/api-keys/[id]/index.ts index 177ba289d9..f5f1a31ff2 100644 --- a/pages/api/api-keys/[id]/index.ts +++ b/pages/api/api-keys/[id]/index.ts @@ -1,9 +1,9 @@ import prisma from "@calcom/prisma"; -import { ApiKey } from "@calcom/prisma/client"; +import { ApiKey } from "@prisma/client"; import type { NextApiRequest, NextApiResponse } from "next"; -import { schemaQueryId, withValidQueryIdString } from "@lib/validations/queryIdString"; +import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/queryIdString"; type ResponseData = { data?: ApiKey; @@ -13,13 +13,13 @@ type ResponseData = { export async function apiKey(req: NextApiRequest, res: NextApiResponse) { const { query, method } = req; - const safe = await schemaQueryId.safeParse(query); + const safe = await schemaQueryIdAsString.safeParse(query); if (safe.success) { if (method === "GET") { const apiKey = await prisma.apiKey.findUnique({ where: { id: safe.data.id } }); if (apiKey) res.status(200).json({ data: apiKey }); - if (!apiKey) res.status(404).json({ message: "Event type not found" }); + if (!apiKey) res.status(404).json({ message: "API key was not found" }); } else { // Reject any other HTTP method than POST res.status(405).json({ message: "Only GET Method allowed" }); diff --git a/pages/api/api-keys/index.ts b/pages/api/api-keys/index.ts index ed0314a9fc..5af005d4e8 100644 --- a/pages/api/api-keys/index.ts +++ b/pages/api/api-keys/index.ts @@ -12,7 +12,7 @@ export default async function apiKey(req: NextApiRequest, res: NextApiResponse res.status(201).json({ data: apiKey })) .catch((error) => { - console.log(error); res.status(400).json({ message: "Could not create apiKey", error: error }) } ) diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.ts index 491989884f..3509fbcd02 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -12,7 +12,6 @@ export default async function eventType(req: NextApiRequest, res: NextApiRespons const eventTypes = await prisma.eventType.findMany(); res.status(200).json({ data: { ...eventTypes } }); } catch (error) { - console.log(error); // FIXME: Add zod for validation/error handling res.status(400).json({ error: error }); } diff --git a/pages/api/users/index.ts b/pages/api/users/index.ts index 3d03dcf205..119ce2c708 100644 --- a/pages/api/users/index.ts +++ b/pages/api/users/index.ts @@ -12,7 +12,6 @@ export default async function user(req: NextApiRequest, res: NextApiResponse