Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get ZodError in json

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

  ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading