Validating js
Answered
Anay-208 posted this in #help-forum
Anay-208OP
I'm using
validate.js to validate a object. However, I'm facing a problem12 Replies
Anay-208OP
const cartItemConstraints = {
_id: {
presence: true,
type: 'string',
},
quantity: {
presence: true,
numericality: {
onlyInteger: true,
greaterThan: 0,
},
},
options: {
presence: true,
type: 'object',
size: {
presence: true,
type: 'string',
},
type: {
presence: true,
type: 'string',
},
color: {
presence: true,
type: 'string',
},
},
};Now, I need to reuse type, but I can't
so what can I do?
this is my ts schema:
export interface CartItem {
_id: string;
options: { size: string; type: string; color: string };
quantity: number;
}Anay-208OP
I'll see this, thanks
So would you recommend any changes in this code:
import { z } from 'zod';
interface Body extends Record<string, any>{
items?: CartItem[] | any;
}
const CartItemSchema = z.object({
_id: z.string(),
quantity: z.number().int().positive(),
options: z.object({
size: z.string(),
type: z.string(),
color: z.string(),
}),
});
const BodySchema = z.object({
items: z.array(CartItemSchema),
});
export async function GET(request: NextRequest) {
const body: Body = await request.json();
try {
BodySchema.parse(body);
} catch (error) {
return NextResponse.json({message: "Invalid request body", errors: error}, {status: 400});
}
// ...
}@Anay-208 So would you recommend any changes in this code:
ts
import { z } from 'zod';
interface Body extends Record<string, any>{
items?: CartItem[] | any;
}
const CartItemSchema = z.object({
_id: z.string(),
quantity: z.number().int().positive(),
options: z.object({
size: z.string(),
type: z.string(),
color: z.string(),
}),
});
const BodySchema = z.object({
items: z.array(CartItemSchema),
});
export async function GET(request: NextRequest) {
const body: Body = await request.json();
try {
BodySchema.parse(body);
} catch (error) {
return NextResponse.json({message: "Invalid request body", errors: error}, {status: 400});
}
// ...
}
yes, with zod, you can infer the type from schema
type Body = z.infer<typeof BodySchema>also merging two schema...etc..
Anay-208OP
so by doing this, I can get the same type in ts, right?
const CartItemSchema = z.object({
_id: z.string(),
quantity: z.number().int().positive(),
options: z.object({
size: z.string(),
type: z.string(),
color: z.string(),
}),
});
export type CartItem = z.infer<typeof CartItemSchema>;yes
Anay-208OP
Alright, thanks