feat: initial work unifying new endpoint and generating api key

This commit is contained in:
Agusti Fernandez Pardo
2022-04-07 03:29:53 +02:00
parent a1dcfa59bc
commit fc2978a61b
8 changed files with 135 additions and 92 deletions
-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
+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"]);
+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 -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,
+44 -13
View File
@@ -3,8 +3,8 @@ 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 { schemaAttendeeBodyParams, schemaAttendeePublic, withValidAttendee } from "@lib/validations/attendee";
/**
* @swagger
@@ -20,18 +20,49 @@ 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;
if (method === "GET") {
const attendees = await prisma.attendee.findMany();
const data = attendees.map((attendee) => schemaAttendeePublic.parse(attendee));
if (data) res.status(200).json({ data });
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) throw new Error("Invalid request body", safe.error);
if (data) res.status(200).json({ data });
else
(error: Error) =>
res.status(404).json({
message: "No Attendees were found",
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,
});
} else res.status(405).json({ message: `Method ${method} not allowed` });
}
export default withMiddleware("HTTP_GET")(allAttendees);
export default withMiddleware("HTTP_GET_OR_POST")(withValidAttendee(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));