Home > OS >  How to get ZodError in json
How to get ZodError in json

Time:06-24

I'm trying to get zod validation errors in json when i test it in insomnia, but am getting it only in terminal and in insomnia it's telling me Error: Couldn't connect to server i saw some examples and everywhere it's worked... don't understand why it's not working...

my register method

export const register = async (req: Request, res: Response) => {
  const payloadSchema = z
    .object({
      firstname: z.string({
        required_error: "Firstname is required",
        invalid_type_error: "Title must be a string",
      }),
      lastname: z.string({
        required_error: "Lastname is required",
        invalid_type_error: "Title must be a string",
      }),
      email: z
        .string({ required_error: "Email is required" })
        .email({ message: "Invalid email address" }),
      password: z.string(),
      confirm: z.string(),
    })
    .refine((data) => data.password === data.confirm, {
      message: "Passwords don't match",
      path: ["confirm"], 
    });

  const parsedData = await payloadSchema.parseAsync(req.body);

  try {
    const result = await User.findOne({ where: { email: parsedData.email } });

    if (result) {
      return res.status(400).json({
        success: false,
        error: "User already exists",
      });
    }

    const user = new User();
    user.firstname = parsedData.firstname;
    user.lastname = parsedData.lastname;
    user.email = parsedData.email;
    user.password = parsedData.password;
    await user.save();

    const accessToken = jwt.sign(
      { userId: user.id },
      process!.env!.TOKEN_SECRET!
    );

    return res.status(200).json({
      success: true,
      createdUser: user,
      accessToken: accessToken,
    });
  } catch (e) {
    if (e instanceof ZodError) {
      return res.status(400).json({
        success: false,
        error: e.flatten(),
      });
    } else if (e instanceof Error) {
      return res.status(400).json({
        message: e.message,
      });
    }
  }
};

so what's am doing wrong, and how can i fix it? thanks for attention.

CodePudding user response:

const parsedData = await payloadSchema.parseAsync(req.body);

The parseAsync call from Zod will throw an error if the validation fails, but in your code it's outside the try/catch block, try moving it inside:

try {
  const parsedData = await payloadSchema.parseAsync(req.body);
 
  const result = await User.findOne({ where: { email: parsedData.email } });

  ...
  • Related