Next.js Discord

Discord Forum

Validating js

Answered
Anay-208 posted this in #help-forum
Open in Discord
I'm using validate.js to validate a object. However, I'm facing a problem

12 Replies

  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;
  }
Answer
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});
  }

  // ...
}
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
Alright, thanks