Merge pull request #31 from calcom/feat/unify-new-endpoint

This commit is contained in:
Agusti Fernandez
2022-04-08 21:03:57 +02:00
committed by GitHub
24 changed files with 443 additions and 228 deletions
+1
View File
@@ -0,0 +1 @@
API_KEY_PREFIX=cal_
-26
View File
@@ -1,26 +0,0 @@
name: Check types
on:
pull_request:
branches:
- main
jobs:
types:
name: Check types
strategy:
matrix:
node: ["14.x"]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout repo
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Use Node ${{ matrix.node }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node }}
- run: yarn
- run: yarn type-check
+1 -1
View File
@@ -2,7 +2,7 @@ import { nanoid } from "nanoid";
import { NextMiddleware } from "next-api-middleware";
export const addRequestId: NextMiddleware = async (_req, res, next) => {
// Apply header
// Apply header with unique ID to every request
res.setHeader("Calcom-Response-ID", nanoid());
// Let remaining middleware and API route execute
await next();
+4 -5
View File
@@ -6,10 +6,9 @@ export const captureErrors: NextMiddleware = async (_req, res, next) => {
// Catch any errors that are thrown in remaining
// middleware and the API route handler
await next();
} catch (err) {
Sentry.captureException(err);
console.log(err);
res.status(400).json({ message: "Something went wrong", error: err });
// res.json({ error: err });
} catch (error) {
Sentry.captureException(error);
console.log(error);
res.status(400).json({ message: "Something went wrong", error });
}
};
+4 -1
View File
@@ -10,7 +10,9 @@ export const httpMethod = (allowedHttpMethod: "GET" | "POST" | "PATCH" | "DELETE
}
};
};
// Made this so we can support several HTTP Methods in one route and use it there.
// Could be further extracted into a third function or refactored into one.
// that checks if it's just a string or an array and apply the correct logic to both cases.
export const httpMethods = (allowedHttpMethod: string[]): NextMiddleware => {
return async function (req, res, next) {
if (allowedHttpMethod.map((method) => method === req.method)) {
@@ -27,3 +29,4 @@ export const HTTP_GET = httpMethod("GET");
export const HTTP_PATCH = httpMethod("PATCH");
export const HTTP_DELETE = httpMethod("DELETE");
export const HTTP_GET_DELETE_PATCH = httpMethods(["GET", "DELETE", "PATCH"]);
export const HTTP_GET_OR_POST = httpMethods(["GET", "POST"]);
+21 -11
View File
@@ -1,24 +1,34 @@
import { NextMiddleware } from "next-api-middleware";
// import { nanoid } from "nanoid";
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
import prisma from "@calcom/prisma";
const dateInPast = function (firstDate: Date, secondDate: Date) {
// Used to check if the API key is not expired, could be extracted if reused. but not for now.
export const dateInPast = function (firstDate: Date, secondDate: Date) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;
}
};
const today = new Date();
// This verifies the API key and sets the user if it is valid.
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" });
const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.apiKey as string } });
if (!apiKey) {
res.status(401).json({ error: "Your api key is not valid" });
throw new Error("No api key found");
}
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) {
res.setHeader("Calcom-User-ID", apiKey.userId);
await next();
} else res.status(401).json({ error: "Your api key is not valid" });
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
const hashedKey = hashAPIKey(strippedApiKey);
await prisma.apiKey
.findUnique({ where: { hashedKey } })
.then(async (apiKey) => {
if (!apiKey) {
res.status(401).json({ error: "You did not provide an api key" });
throw new Error("No api key found");
}
if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey?.userId);
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) await next();
})
.catch((error) => {
res.status(401).json({ error: "Your api key is not valid" });
});
};
-23
View File
@@ -1,23 +0,0 @@
// Make a middleware that adds a cost to running the request
// by calling stripeSubscription addCost() * pricePerBooking
// Initially to test out 0,5 cent per booking via API call
// withCost(5)(endpoint)
// Should add a charge of 0.5 cent per booking to the subscription of the user making the request
import { NextMiddleware } from "next-api-middleware";
export const withCost = (priceInCents: number): NextMiddleware => {
return async function (req, res, next) {
console.log(req.headers);
if (
priceInCents > 0
// && stripeCustomerId && stripeSubscriptionId
) {
console.log(priceInCents);
// if (req.method === allowedHttpMethod || req.method == "OPTIONS") {
await next();
} else {
res.status(405).json({ message: `We weren't able to process the payment for this transaction` });
res.end();
}
};
};
+9 -1
View File
@@ -2,11 +2,19 @@ import { label } from "next-api-middleware";
import { addRequestId } from "./addRequestid";
import { captureErrors } from "./captureErrors";
import { HTTP_POST, HTTP_DELETE, HTTP_PATCH, HTTP_GET, HTTP_GET_DELETE_PATCH } from "./httpMethods";
import {
HTTP_POST,
HTTP_DELETE,
HTTP_PATCH,
HTTP_GET,
HTTP_GET_OR_POST,
HTTP_GET_DELETE_PATCH,
} from "./httpMethods";
import { verifyApiKey } from "./verifyApiKey";
const withMiddleware = label(
{
HTTP_GET_OR_POST,
HTTP_GET_DELETE_PATCH,
HTTP_GET,
HTTP_PATCH,
+2
View File
@@ -62,6 +62,8 @@ export type SelectedCalendarsResponse = BaseResponse & {
export type AttendeeResponse = BaseResponse & {
data?: Partial<Attendee>;
};
// Grouping attendees in booking arrays for now,
// later might remove endpoint and move to booking endpoint altogether.
export type AttendeesResponse = BaseResponse & {
data?: Partial<Attendee>[];
};
+3
View File
@@ -0,0 +1,3 @@
import { NextApiResponse } from "next";
export const getCalcomUserId = (res: NextApiResponse): number => res.getHeader("x-calcom-user-id") as number;
+1
View File
@@ -8,6 +8,7 @@ export const schemaAttendeeBaseBodyParams = Attendee.omit({ id: true }).partial(
export const schemaAttendeePublic = Attendee.omit({});
const schemaAttendeeRequiredParams = z.object({
bookingId: z.any(),
email: z.string().email(),
name: z.string(),
timeZone: z.string(),
+2 -2
View File
@@ -2,9 +2,9 @@ import { withValidation } from "next-validations";
import { _PaymentModel as Payment } from "@calcom/prisma/zod";
// FIXME: Payment seems a delicate endpoint, do we need to remove anything here?
export const schemaPaymentBodyParams = Payment.omit({ id: true });
export const schemaPaymentPublic = Payment.omit({});
export const schemaPaymentPublic = Payment.omit({ externalId: true });
export const withValidPayment = withValidation({
schema: schemaPaymentBodyParams,
+1 -1
View File
@@ -6,7 +6,7 @@ export const baseApiParams = z
.object({
// since we added apiKey as query param this is required by next-validations helper
// for query params to work properly and not fail.
apiKey: z.string().cuid().optional(),
apiKey: z.string().optional(),
// version required for supporting /v1/ redirect to query in api as *?version=1
version: z.string().optional(),
})
+1 -1
View File
@@ -1,6 +1,6 @@
// 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", "@calcom/lib"]);
const withTM = require("next-transpile-modules")(["@calcom/prisma", "@calcom/lib", "@calcom/ee"]);
// use something like withPlugins([withTM], {}) if more plugins added later.
+61 -13
View File
@@ -3,8 +3,9 @@ import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import { AttendeesResponse } from "@lib/types";
import { schemaAttendeePublic } from "@lib/validations/attendee";
import { AttendeeResponse, AttendeesResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee";
/**
* @swagger
@@ -20,18 +21,65 @@ import { schemaAttendeePublic } from "@lib/validations/attendee";
* description: Authorization information is missing or invalid.
* 404:
* description: No attendees were found
* post:
* summary: Creates a new attendee
* tags:
* - attendees
* responses:
* 201:
* description: OK, attendee created
* model: Attendee
* 400:
* description: Bad request. Attendee body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function allAttendees(_: NextApiRequest, res: NextApiResponse<AttendeesResponse>) {
const attendees = await prisma.attendee.findMany();
const data = attendees.map((attendee) => schemaAttendeePublic.parse(attendee));
async function createOrlistAllAttendees(
req: NextApiRequest,
res: NextApiResponse<AttendeesResponse | AttendeeResponse>
) {
const { method } = req;
const userId = getCalcomUserId(res);
// Here we make sure to only return attendee's of the user's own bookings.
const userBookings = await prisma.booking.findMany({
where: {
userId,
},
include: {
attendees: true,
},
});
const userBookingsAttendees = userBookings.map((booking) => booking.attendees).flat();
if (method === "GET") {
if (userBookingsAttendees) res.status(200).json({ data: userBookingsAttendees });
else
(error: Error) =>
res.status(404).json({
message: "No Attendees were found",
error,
});
} else if (method === "POST") {
const safe = schemaAttendeeBodyParams.safeParse(req.body);
if (!safe.success) {
console.log(safe.error);
throw new Error("Invalid request body", safe.error);
}
const bookingId = safe.data.bookingId;
delete safe.data.bookingId;
const noBookingId = safe.data;
const attendee = await prisma.attendee.create({
data: { ...noBookingId, booking: { connect: { id: parseInt(bookingId as string) } } },
});
const data = schemaAttendeePublic.parse(attendee);
if (data) res.status(200).json({ data });
else
(error: Error) =>
res.status(404).json({
message: "No Attendees were found",
error,
});
if (data) res.status(201).json({ data, message: "Attendee created successfully" });
else
(error: Error) =>
res.status(400).json({
message: "Could not create new attendee",
error,
});
} else res.status(405).json({ message: `Method ${method} not allowed` });
}
export default withMiddleware("HTTP_GET")(allAttendees);
export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllAttendees);
-41
View File
@@ -1,41 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import type { AttendeeResponse } from "@lib/types";
import { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee";
/**
* @swagger
* /api/attendees/new:
* post:
* summary: Creates a new attendee
* tags:
* - attendees
* responses:
* 201:
* description: OK, attendee created
* model: Attendee
* 400:
* description: Bad request. Attendee body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createAttendee(req: NextApiRequest, res: NextApiResponse<AttendeeResponse>) {
const safe = schemaAttendeeBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body", safe.error);
const attendee = await prisma.attendee.create({ data: safe.data });
const data = schemaAttendeePublic.parse(attendee);
if (data) res.status(201).json({ data, message: "Attendee created successfully" });
else
(error: Error) =>
res.status(400).json({
message: "Could not create new attendee",
error,
});
}
export default withMiddleware("HTTP_POST")(withValidAttendee(createAttendee));
+8 -8
View File
@@ -5,13 +5,16 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import type { PaymentResponse } from "@lib/types";
import { schemaPaymentBodyParams, schemaPaymentPublic } from "@lib/validations/payment";
import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/shared/queryIdString";
import {
schemaQueryIdParseInt,
withValidQueryIdTransformParseInt,
} from "@lib/validations/shared/queryIdTransformParseInt";
/**
* @swagger
* /api/payments/{id}:
* get:
* summary: Get a payment by ID
* summary: Get an payment by ID
* parameters:
* - in: path
* name: id
@@ -78,17 +81,14 @@ import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/
*/
export async function paymentById(req: NextApiRequest, res: NextApiResponse<PaymentResponse>) {
const { method, query, body } = req;
const safeQuery = await schemaQueryIdAsString.safeParse(query);
const safeQuery = await schemaQueryIdParseInt.safeParse(query);
const safeBody = await schemaPaymentBodyParams.safeParse(body);
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
const [userId, teamId] = safeQuery.data.id.split("_");
switch (method) {
case "GET":
await prisma.payment
.findUnique({
where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } },
})
.findUnique({ where: { id: safeQuery.data.id } })
.then((payment) => schemaPaymentPublic.parse(payment))
.then((data) => res.status(200).json({ data }))
.catch((error: Error) =>
@@ -127,4 +127,4 @@ export async function paymentById(req: NextApiRequest, res: NextApiResponse<Paym
}
}
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdString(paymentById));
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(paymentById));
+68
View File
@@ -0,0 +1,68 @@
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, withValidPayment } from "@lib/validations/payment";
/**
* @swagger
* /api/payments:
* get:
* summary: Get all payments
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No payments were found
* post:
* summary: Creates a new payment
* tags:
* - payments
* responses:
* 201:
* description: OK, payment created
* model: Payment
* 400:
* description: Bad request. Payment body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createOrlistAllPayments(
req: NextApiRequest,
res: NextApiResponse<PaymentsResponse | PaymentResponse>
) {
const { method } = req;
if (method === "GET") {
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") {
const safe = schemaPaymentBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body");
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")(withValidPayment(createOrlistAllPayments));
+68
View File
@@ -0,0 +1,68 @@
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, withValidPayment } from "@lib/validations/payment";
/**
* @swagger
* /api/payments:
* get:
* summary: Get all payments
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No payments were found
* post:
* summary: Creates a new payment
* tags:
* - payments
* responses:
* 201:
* description: OK, payment created
* model: Payment
* 400:
* description: Bad request. Payment body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createOrlistAllPayments(
req: NextApiRequest,
res: NextApiResponse<PaymentsResponse | PaymentResponse>
) {
const { method } = req;
if (method === "GET") {
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") {
const safe = schemaPaymentBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body");
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")(withValidPayment(createOrlistAllPayments));
+68
View File
@@ -0,0 +1,68 @@
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, withValidPayment } from "@lib/validations/payment";
/**
* @swagger
* /api/payments:
* get:
* summary: Get all payments
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No payments were found
* post:
* summary: Creates a new payment
* tags:
* - payments
* responses:
* 201:
* description: OK, payment created
* model: Payment
* 400:
* description: Bad request. Payment body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createOrlistAllPayments(
req: NextApiRequest,
res: NextApiResponse<PaymentsResponse | PaymentResponse>
) {
const { method } = req;
if (method === "GET") {
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") {
const safe = schemaPaymentBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body");
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")(withValidPayment(createOrlistAllPayments));
+42 -39
View File
@@ -4,6 +4,7 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import type { UserResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getUserFromHeader";
import {
schemaQueryIdParseInt,
withValidQueryIdTransformParseInt,
@@ -14,7 +15,7 @@ import { schemaUserBodyParams, schemaUserPublic } from "@lib/validations/user";
* @swagger
* /api/users/{id}:
* get:
* summary: Get a user by ID
* summary: Get a user by ID, returns your user if regular user.
* parameters:
* - in: path
* name: id
@@ -84,47 +85,49 @@ export async function userById(req: NextApiRequest, res: NextApiResponse<UserRes
const safeQuery = await schemaQueryIdParseInt.safeParse(query);
const safeBody = await schemaUserBodyParams.safeParse(body);
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
const userId = getCalcomUserId(res);
if (safeQuery.data.id === userId) {
switch (method) {
case "GET":
await prisma.user
.findUnique({ where: { id: safeQuery.data.id } })
.then((user) => schemaUserPublic.parse(user))
.then((data) => res.status(200).json({ data }))
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
switch (method) {
case "GET":
await prisma.user
.findUnique({ where: { id: safeQuery.data.id } })
.then((user) => schemaUserPublic.parse(user))
.then((data) => res.status(200).json({ data }))
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
case "PATCH":
if (!safeBody.success) throw new Error("Invalid request body");
await prisma.user
.update({
where: { id: safeQuery.data.id },
data: safeBody.data,
})
.then((user) => schemaUserPublic.parse(user))
.then((data) => res.status(200).json({ data }))
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
case "PATCH":
if (!safeBody.success) throw new Error("Invalid request body");
await prisma.user
.update({
where: { id: safeQuery.data.id },
data: safeBody.data,
})
.then((user) => schemaUserPublic.parse(user))
.then((data) => res.status(200).json({ data }))
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
case "DELETE":
await prisma.user
.delete({ where: { id: safeQuery.data.id } })
.then(() =>
res.status(200).json({ message: `User with id: ${safeQuery.data.id} deleted successfully` })
)
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
case "DELETE":
await prisma.user
.delete({ where: { id: safeQuery.data.id } })
.then(() =>
res.status(200).json({ message: `User with id: ${safeQuery.data.id} deleted successfully` })
)
.catch((error: Error) =>
res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error })
);
break;
default:
res.status(405).json({ message: "Method not allowed" });
break;
}
default:
res.status(405).json({ message: "Method not allowed" });
break;
}
} else res.status(401).json({ message: "Unauthorized" });
}
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(userById));
+10 -4
View File
@@ -4,13 +4,14 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import { UsersResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaUserPublic } from "@lib/validations/user";
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* summary: Get all users (admin only), returns your user if regular user.
* tags:
* - users
* responses:
@@ -21,10 +22,14 @@ import { schemaUserPublic } from "@lib/validations/user";
* 404:
* description: No users were found
*/
async function allUsers(_: NextApiRequest, res: NextApiResponse<UsersResponse>) {
const users = await prisma.user.findMany();
async function allUsers(req: NextApiRequest, res: NextApiResponse<UsersResponse>) {
const userId = getCalcomUserId(res);
const users = await prisma.user.findMany({
where: {
id: userId,
},
});
const data = users.map((user) => schemaUserPublic.parse(user));
if (data) res.status(200).json({ data });
else
(error: Error) =>
@@ -33,5 +38,6 @@ async function allUsers(_: NextApiRequest, res: NextApiResponse<UsersResponse>)
error,
});
}
// No POST endpoint for users for now as a regular user you're expected to signup.
export default withMiddleware("HTTP_GET")(allUsers);
-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 { UserResponse } from "@lib/types";
import { schemaUserBodyParams, schemaUserPublic, withValidUser } from "@lib/validations/user";
/**
* @swagger
* /api/users/new:
* post:
* summary: Add a new user
* consumes:
* - application/json
* parameters:
* - in: body
* name: user
* description: The user to edit
* schema:
* type: object
* $ref: '#/components/schemas/User'
* required: true
* tags:
* - users
* responses:
* 201:
* description: OK, user created
* model: User
* 400:
* description: Bad request. User body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createUser(req: NextApiRequest, res: NextApiResponse<UserResponse>) {
const safe = schemaUserBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body", safe.error);
const user = await prisma.user.create({ data: safe.data });
const data = schemaUserPublic.parse(user);
if (data) res.status(201).json({ data, message: "User created successfully" });
else
(error: Error) =>
res.status(400).json({
message: "Could not create new user",
error,
});
}
export default withMiddleware("HTTP_POST")(withValidUser(createUser));
+68
View File
@@ -0,0 +1,68 @@
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, withValidPayment } from "@lib/validations/payment";
/**
* @swagger
* /api/payments:
* get:
* summary: Get all payments
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No payments were found
* post:
* summary: Creates a new payment
* tags:
* - payments
* responses:
* 201:
* description: OK, payment created
* model: Payment
* 400:
* description: Bad request. Payment body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
async function createOrlistAllPayments(
req: NextApiRequest,
res: NextApiResponse<PaymentsResponse | PaymentResponse>
) {
const { method } = req;
if (method === "GET") {
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") {
const safe = schemaPaymentBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body");
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")(withValidPayment(createOrlistAllPayments));