Feat: event-types and tests

This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-25 06:54:57 +01:00
1 parent 2e2f6a5e57
commit a2817a2fee
16 files changed
+15892 -205

No files matched your search

-1
View File
@@ -1 +0,0 @@
module.exports = require("@calcom/config/eslint-preset");
+15
View File
@@ -0,0 +1,15 @@
// FIXME: import eslint-config-calcom-base from '@calcom/config/eslint
{
"root": true,
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@next/next/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": { "project": ["./tsconfig.json"] },
"plugins": [
"@typescript-eslint"
],
"ignorePatterns": ["src/**/*.test.ts", "src/frontend/generated/*"]
}
+20 -4
View File
@@ -2,7 +2,7 @@
## This will be the new public enterprise-only API
This is the public REST api for cal.com.
This is the public REST api for cal.com
## NextJS + TypeScript
@@ -12,14 +12,30 @@ It's a barebones **NextJS** + **TypeScript** project leveraging the nextJS API w
It doesn't have react or react-dom as a dependency, and will only be used by a redirect as a folder or subdomain on cal.com with maybe a v1 tag like:
- `v1.api.cal.com`
- `api.cal.com/v1`
- `app.cal.com/api/v1/`
- `api.cal.com/api/v1`
## API Endpoint Validation
## API Endpoint Validation
### Zod
The API uses `zod` library like our main web repo. It validates that either GET query parameters or POST body content's are valid and up to our spec. It gives appropiate errors when parsing result's with schemas.
### Next Validations
[Next-Validations Docs](https://next-validations.productsway.com/)
[Next-Validations Repo](https://github.com/jellydn/next-validations)
We also use this useful helper library that let's us wrap our endpoints in a validate HOC that checks the req against our validation schema built out with zod for either query and / or body's requests.
## Testing with Jest + node-mocks-http
We aim to provide a fully tested API for our peace of mind, this is accomplished by using jest + node-mocks-http
## Next.config.js
### Redirects
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=*
@@ -0,0 +1,95 @@
import handleEventEdit from "@api/event-types/[id]/edit";
import { createMocks } from "node-mocks-http";
import prisma from "@calcom/prisma";
describe("PATCH /api/event-types/[id]/edit with valid id and body updates an event-type", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
method: "PATCH",
query: {
id: "2",
},
body: {
title: "Updated title",
slug: "updated-slug",
length: 1,
},
});
const event = await prisma.eventType.findUnique({ where: { id: 2 } });
await handleEventEdit(req, res);
expect(res._getStatusCode()).toBe(200);
if (event) event.title = "Updated title";
expect(JSON.parse(res._getData())).toStrictEqual({ data: event });
});
});
describe("PATCH /api/event-types/[id]/edit with invalid id returns 404", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
method: "PATCH",
query: {
id: "0",
},
body: {
title: "Updated title",
slug: "updated-slug",
length: 1,
},
});
const event = await prisma.eventType.findUnique({ where: { id: 2 } });
await handleEventEdit(req, res);
expect(res._getStatusCode()).toBe(404);
if (event) event.title = "Updated title";
expect(JSON.parse(res._getData())).toStrictEqual({ "error": {
"clientVersion": "3.10.0",
"code": "P2025",
"meta": {
"cause": "Record to update not found.",
},
},
"message": "Event type with ID 0 not found and wasn't updated", });
});
});
describe("PATCH /api/event-types/[id]/edit with valid id and no body returns 400 error and zod validation errors", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
method: "PATCH",
query: {
id: "2",
},
});
await handleEventEdit(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"}]);
});
});
describe("POST /api/event-types/[id]/edit fails, only PATCH allowed", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
method: "POST", // This POST method is not allowed
query: {
id: "1",
},
body: {
title: "Updated title",
slug: "updated-slug",
length: 1,
},
});
await handleEventEdit(req, res);
expect(res._getStatusCode()).toBe(405);
expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only PATCH Method allowed for updating event-types" });
});
});
afterAll((done) => {
prisma.$disconnect().then();
done();
});
@@ -1,9 +1,8 @@
import handleEvent from "@api/event-types/[id]";
import { createMocks } from "node-mocks-http";
import prisma from "@calcom/prisma";
import handleEvent from "../../../pages/api/event-types/[id]";
describe("GET /api/event-types/[id] with valid id as string returns an event-type", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
@@ -56,7 +55,7 @@ describe("GET /api/event-types/[id] an id not present in db like 0, throws 404 n
await handleEvent(req, res);
expect(res._getStatusCode()).toBe(404);
expect(JSON.parse(res._getData())).toStrictEqual({ error: "Event type not found" });
expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" });
});
});
@@ -71,24 +70,7 @@ describe("POST /api/event-types/[id] fails, only GET allowed", () => {
await handleEvent(req, res);
expect(res._getStatusCode()).toBe(405);
expect(JSON.parse(res._getData())).toStrictEqual({ error: "Only GET Method allowed" });
});
});
describe("PATCH /api/event-types/[id]/edit with valid id and body updates an event-type", () => {
it("returns a message with the specified events", async () => {
const { req, res } = createMocks({
method: "PATCH",
query: {
id: "1",
},
});
const event = await prisma.eventType.findUnique({ where: { id: 1 } });
await handleEvent(req, res);
expect(res._getStatusCode()).toBe(200);
if (event) event.title = "Updated title";
expect(JSON.parse(res._getData())).toStrictEqual({ data: event });
expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" });
});
});
+10 -72
View File
@@ -4,17 +4,8 @@
*/
const config = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
coverageDirectory: "./coverage",
collectCoverage: true,
// An array of regexp pattern strings used to skip coverage collection
@@ -26,12 +17,12 @@ const config = {
// coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
coverageReporters: [
"json",
"text",
"lcov",
"clover"
],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
@@ -40,7 +31,7 @@ const config = {
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
errorOnDeprecated: true,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
@@ -55,68 +46,15 @@ const config = {
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
moduleNameMapper: {
"^@lib/(.*)$": "<rootDir>/lib/$1",
"^@api/(.*)$": "<rootDir>/pages/api/$1",
},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
@@ -1,6 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schema = z
const schemaEventType = z
.object({
title: z.string().min(3),
slug: z.string().min(3),
@@ -8,5 +9,10 @@ const schema = z
description: z.string().min(3).optional(),
})
.strict(); // Adding strict so that we can disallow passing in extra fields
const withValidEventType = withValidation({
schema: schemaEventType,
type: "Zod",
mode: "body",
});
export default schema;
export { schemaEventType, withValidEventType };
@@ -1,8 +1,9 @@
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 schema = z
const schemaQueryId = z
.object({
// since nextjs parses query params as strings,
// we need to cast them to numbers using z.transform() and parseInt()
@@ -12,4 +13,11 @@ const schema = z
.transform((id) => parseInt(id)),
})
.strict();
export default schema;
const withValidQueryId = withValidation({
schema: schemaQueryId,
type: "Zod",
mode: "query",
});
export { schemaQueryId, withValidQueryId };
+4 -3
View File
@@ -12,7 +12,7 @@
"build": "next build",
"lint": "next lint",
"lint-fix": "next lint --fix",
"test": "jest --detectOpenHandles",
"test": "jest --detectOpenHandles --verbose",
"type-check": "tsc --pretty --noEmit",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"prepare": "husky install",
@@ -24,13 +24,14 @@
"@babel/preset-typescript": "^7.16.7",
"@calcom/prisma": "*",
"@calcom/tsconfig": "*",
"@typescript-eslint/eslint-plugin": "^5.16.0",
"babel-jest": "^27.5.1",
"husky": "^7.0.4",
"jest": "^27.5.1",
"node-mocks-http": "^1.11.0",
"typescript": "^4.6.3"
"node-mocks-http": "^1.11.0"
},
"dependencies": {
"typescript": "^4.6.3",
"next": "^12.1.0",
"next-validations": "^0.1.11",
"zod": "^3.14.2"
+7 -14
View File
@@ -1,19 +1,18 @@
import { PrismaClient, EventType } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { withValidation } from "next-validations";
import schema from "@lib/validation/queryIdTransformParseInt";
import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt";
const prisma = new PrismaClient();
type ResponseData = {
message?: string;
error?: any;
error?: unknown;
};
export async function eventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { query, method } = req;
const safe = await schema.safeParse(query);
const safe = await schemaQueryId.safeParse(query);
if (safe.success) {
if (method === "DELETE") {
// DELETE WILL DELETE THE EVENT TYPE
@@ -25,19 +24,13 @@ export async function eventType(req: NextApiRequest, res: NextApiResponse<Respon
})
.catch((error) => {
// This catches the error thrown by prisma.eventType.delete() if the resource is not found.
res.status(400).json({ error: error });
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({ error: "Only DELETE Method allowed in /event-types/[id]/delete endpoint" });
res.status(405).json({ message: "Only DELETE Method allowed in /event-types/[id]/delete endpoint" });
}
}
}
const validate = withValidation({
schema,
type: "Zod",
mode: "query",
});
export default validate(eventType);
export default withValidQueryId(eventType);
+18 -22
View File
@@ -1,41 +1,37 @@
import { PrismaClient, EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { withValidation } from "next-validations";
import schema from "@lib/validation/eventType";
import schemaQuery from "@lib/validation/queryIdTransformParseInt";
import { schemaEventType, withValidEventType } from "@lib/validations/eventType";
import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt";
const prisma = new PrismaClient();
type ResponseData = {
data?: EventType;
error?: any;
message?: string;
error?: unknown;
};
export async function editEventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { query, body, method } = req;
const safeQuery = await schemaQuery.safeParse(query);
const safeBody = await schema.safeParse(body);
const safeQuery = await schemaQueryId.safeParse(query);
const safeBody = await schemaEventType.safeParse(body);
if (safeQuery.success && safeBody.success) {
if (method === "PATCH") {
const event = await prisma.eventType.update({
if (method === "PATCH") {
if (safeQuery.success && safeBody.success) {
await prisma.eventType.update({
where: { id: safeQuery.data.id },
data: { ...safeBody.data },
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 })
});
if (event) res.status(200).json({ data: event });
if (!event) res.status(404).json({ error: "Event type not found" });
} else {
// Reject any other HTTP method than POST
res.status(405).json({ error: "Only GET Method allowed" });
}
} else {
// Reject any other HTTP method than POST
res.status(405).json({ message: "Only PATCH Method allowed for updating event-types" });
}
}
const validate = withValidation({
schema,
type: "Zod",
mode: "body",
});
export default validate(editEventType);
export default withValidQueryId(withValidEventType(editEventType));
+7 -19
View File
@@ -1,43 +1,31 @@
import { PrismaClient, EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { withValidation } from "next-validations";
import schema from "@lib/validation/queryIdTransformParseInt";
import { schemaQueryId, withValidQueryId } from "@lib/validations/queryIdTransformParseInt";
const prisma = new PrismaClient();
type ResponseData = {
data?: EventType;
error?: any;
message?: string;
error?: unknown;
};
export async function eventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { query, method } = req;
const safe = await schema.safeParse(query);
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({ error: "Event type not found" });
} else if (method === "PATCH") {
const event = await prisma.eventType.update({
where: { id: safe.data.id },
data: { title: "Updated title" },
});
if (event) res.status(200).json({ data: event });
if (!event) res.status(404).json({ error: "Event type not found" });
if (!event) res.status(404).json({ message: "Event type not found" });
} else {
// Reject any other HTTP method than POST
res.status(405).json({ error: "Only GET Method allowed" });
res.status(405).json({ message: "Only GET Method allowed" });
}
}
}
const validate = withValidation({
schema,
type: "Zod",
mode: "query",
});
export default validate(eventType);
export default withValidQueryId(eventType);
+1 -1
View File
@@ -4,7 +4,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
const prisma = new PrismaClient();
type ResponseData = {
data?: EventType[];
error?: any;
error?: unknown;
};
export default async function eventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
+3 -11
View File
@@ -1,17 +1,9 @@
import { PrismaClient, EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { withValidation } from "next-validations";
import schema from "@lib/validation/eventType";
import { schemaEventType, withValidEventType } from "@lib/validations/eventType";
const prisma = new PrismaClient();
const validate = withValidation({
schema,
type: "Zod",
mode: "body",
});
type ResponseData = {
data?: EventType;
message?: string;
@@ -21,7 +13,7 @@ type ResponseData = {
async function createEventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { body, method } = req;
if (method === "POST") {
const safe = schema.safeParse(body);
const safe = schemaEventType.safeParse(body);
if (safe.success && safe.data) {
await prisma.eventType
.create({ data: safe.data })
@@ -34,4 +26,4 @@ async function createEventType(req: NextApiRequest, res: NextApiResponse<Respons
}
}
export default validate(createEventType);
export default withValidEventType(createEventType);
-19
View File
@@ -1,19 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import { User } from "@calcom/prisma/client";
type Data = {
message: string;
};
export default async function userId(req: NextApiRequest, res: NextApiResponse<Data>) {
const { id }: { id?: string } = req.query;
if (!id) return res.status(404).json({ message: `User not found` });
const user = await prisma.user.findUnique({
where: {
id: parseInt(id),
},
});
return res.json({ message: `Hello ${user?.name}` });
}
+15691 -14
View File
File diff suppressed because it is too large. Load diff