Comments (2)
To resolve the Zod errors encountered when making requests to the /payments
and /payments/[id]
API endpoints, ensure that the query parameters and the response data conform to the expected schema definitions. Here is a step-by-step approach to troubleshoot and resolve the Zod errors:
-
Validate Query Parameters: Ensure that the query parameters passed to the API endpoints match the expected schema. The
schemaQueryIdParseInt
schema is used to validate and parse theid
parameter. -
Validate Response Data: Ensure that the response data from the database matches the
schemaPaymentPublic
schema. This schema is used to validate the payment data before sending it in the response. Note that theschemaPaymentPublic
schema omits theexternalId
field from the payment data. -
Error Handling: Properly handle and log errors to understand the cause of the Zod validation failures. Implement a Zod exception filter to catch and log detailed error information.
Here is the relevant code snippet with comments to help you understand the validation process:
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import { withMiddleware } from "~/lib/helpers/withMiddleware";
import type { PaymentResponse } from "~/lib/types";
import { schemaPaymentPublic } from "~/lib/validations/payment";
import {
schemaQueryIdParseInt,
withValidQueryIdTransformParseInt,
} from "~/lib/validations/shared/queryIdTransformParseInt";
/**
* @swagger
* /payments/{id}:
* get:
* summary: Find a payment
* parameters:
* - in: query
* name: apiKey
* required: true
* schema:
* type: string
* description: Your API key
* - in: path
* name: id
* schema:
* type: integer
* required: true
* description: ID of the payment to get
* tags:
* - payments
* responses:
* 200:
* description: OK
* 401:
* description: Authorization information is missing or invalid.
* 404:
* description: Payment was not found
*/
export async function paymentById(
{ method, query, userId }: NextApiRequest,
res: NextApiResponse<PaymentResponse>
) {
// Validate and parse the query parameters
const safeQuery = schemaQueryIdParseInt.safeParse(query);
if (safeQuery.success && method === "GET") {
const userWithBookings = await prisma.user.findUnique({
where: { id: userId },
include: { bookings: true },
});
// Fetch and validate the payment data
await prisma.payment
.findUnique({ where: { id: safeQuery.data.id } })
.then((data) => schemaPaymentPublic.parse(data))
.then((payment) => {
// Check if the user is authorized to view the payment
if (!userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) {
res.status(401).json({ message: "Unauthorized" });
} else {
res.status(200).json({ payment });
}
})
.catch((error: Error) =>
res.status(404).json({
message: `Payment with id: ${safeQuery.data.id} not found`,
error,
})
);
} else {
// Handle invalid query parameters
res.status(400).json({ message: "Invalid query parameters" });
}
}
export default withMiddleware("HTTP_GET")(withValidQueryIdTransformParseInt(paymentById));
Additionally, implement a Zod exception filter to catch and log detailed error information:
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import { Catch, HttpStatus, Logger } from "@nestjs/common";
import { Request } from "express";
import { ZodError } from "zod";
import { BAD_REQUEST, ERROR_STATUS } from "@calcom/platform-constants";
import { Response } from "@calcom/platform-types";
@Catch(ZodError)
export class ZodExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger("ZodExceptionFilter");
catch(error: ZodError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const requestId = request.headers["X-Request-Id"];
this.logger.error(`ZodError: ${error.message}`, {
error,
body: request.body,
headers: request.headers,
url: request.url,
method: request.method,
requestId,
});
response.status(HttpStatus.BAD_REQUEST).json({
status: ERROR_STATUS,
timestamp: new Date().toISOString(),
path: request.url,
error: {
code: BAD_REQUEST,
message: error.issues.reduce(
(acc, issue) => `${issue.path.join(".")} - ${issue.message}, ${acc}`,
""
),
},
});
}
}
Ensure that the id
parameter in the query is an integer and that the payment data returned from the database matches the schemaPaymentPublic
schema, which omits the externalId
field. If there are any discrepancies, adjust the input data or the schema definitions accordingly [1][2][3].
To continue talking to Dosu, mention @dosu.
from cal.com.
Second this! Happens on both endpoints for me as well. It seems like an issue/error occurs when running the parse function of _paymentModel in @calcom/prisma/zod. because of data type differences. Critical issue for us since we can't retrieve payment UID for abandoned carts payment links and other payment details for internal reference.
from cal.com.
Related Issues (20)
- [CAL-4044] Reschedule not working for a migrate org member when done from the booking success page
- [CAL-4045] remove cal.ai (email) app
- perf: enable prisma optimize HOT 1
- [CAL-4046] booker: border missing
- [CAL-4048] Make.com Connection - Watch Booking Cancelled Not Working
- Embed graphical bug: Empty scrollbar track rendering unpredictably when there's no overflow HOT 1
- [CAL-4049] Choosing a different location when rescheduling not working HOT 1
- Incorrect app store url in event type page
- [CAL-4051] Erorr with the UI teams HOT 1
- Prevent two people booking one slot, even if first is pending
- Docs: Documentation page for integration with Hubspot is not working
- [CAL-4052] Timezone select should show the selected timezone HOT 4
- app.cal.com refuse to connect on Job posting link
- [CAL-4053] When users opt for annual pricing charged same day
- [CAL-4054] Team ownership change
- Make OOO events editable HOT 1
- add a new feature (delete past events) HOT 2
- Text in Embed Code Becomes Invisible on Selection HOT 3
- [CAL-4055] Not able to book a time on a date that is earlier than today(but actually is today in the browsing timezone) HOT 4
- Hide emails when sending the calendar invite HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cal.com.