cal.pub0.org/templates/endpoints/get_all_and_post.ts

76 lines
2.1 KiB
TypeScript
Raw Normal View History

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 } from "@lib/validations/payment";
2022-04-30 18:53:19 +00:00
async function createOrlistAllPayments(
2022-05-16 21:06:29 +00:00
{ method, body }: NextApiRequest,
2022-04-30 18:53:19 +00:00
res: NextApiResponse<PaymentsResponse | PaymentResponse>
) {
if (method === "GET") {
2022-05-16 21:06:29 +00:00
/**
* @swagger
* /v1/payments:
* get:
* summary: Find all payments
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: No payments were found
2022-04-30 18:53:19 +00:00
*/
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") {
2022-05-16 21:06:29 +00:00
/**
2022-04-30 18:53:19 +00:00
* @swagger
* /v1/payments:
* post:
* summary: Creates a new payment
* tags:
* - payments
* responses:
* 201:
* description: OK, payment created
* 400:
* description: Bad request. Payment body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
2022-04-30 18:53:19 +00:00
const safe = schemaPaymentBodyParams.safeParse(body);
2022-05-17 17:33:18 +00:00
if (!safe.success) {
res.status(400).json({ message: "Invalid request body" });
return;
}
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")(createOrlistAllPayments);