0

im trying to use this function convertError to convert error from zod, but i always get that return: TypeError: Cannot read property 'formatError' of undefined

import { IMiddlewaresRules } from "../IMiddlewaresRules";
import { Request, Response, NextFunction } from "express";
import { figureBodySchema } from "../zodschemas/schemasZod";
import { ZodError } from "zod";

class FormatError {
  convertError(
    err: ZodError
  ): Array<{ message: string; key: (string | number)[]; code: number }> {
    return err.issues.map((err) => {
      const error = {
        message: err.message,
        key: err.path,
        code: 400,
      };
      return error;
    });
  }
}

export class VerifyRequestsBody implements IMiddlewaresRules {
  constructor(private formatError: FormatError) {}

  verifyBodyFigure(
    req: Request,
    res: Response,
    next: NextFunction
  ): Response | any {
    const { data } = req.body;

    try {
      figureBodySchema.parse(data);
    } catch (err) {
      if (err instanceof ZodError) {
        return res.status(400).json(this.formatError.convertError(err));
      }
    }
    next();
  }

}

i don't understand why this happen, i already define the function before

full code here: https://github.com/DanielTrybe/backend-figures/tree/1.2.0-middleware

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Daniel Roberto
  • 101
  • 1
  • 7
  • How do you call `verifyBodyFigure`? How do you instantiate `VerifyRequestsBody`? – Bergi Oct 09 '22 at 17:16
  • its a node, my code is here https://github.com/DanielTrybe/backend-figures/tree/1.2.0-middleware and i call with a post – Daniel Roberto Oct 09 '22 at 17:22
  • @HeikoTheißen it's typescript actually, and by annotating the constructor parameter with `private` the property will be created implicitly – Bergi Oct 09 '22 at 17:27
  • [Here's your problem](https://github.com/DanielTrybe/backend-figures/blob/a1770f6c786a73a7084daf3bf43d79fbcae3e0e8/src/routes/post/routes.ts#L6-L11). You did not bind the methods to the instance. – Bergi Oct 09 '22 at 17:30
  • i dont understand, all works without that convertError, if i set the map in catch like that: if (err instanceof ZodError) { return res.status(400).json( err.issues.map((err) => { const error = { message: err.message, key: err.path, code: 400, }; return error; }) ); } , it works – Daniel Roberto Oct 09 '22 at 17:36
  • The problem is that you're attempting to reference `this.formatError` in an unbound method. The problem is not with `convertError` itself, or even to do with zod. – Bergi Oct 09 '22 at 17:39
  • i'm confused, but how i bound that function to work like a help function for this class? – Daniel Roberto Oct 09 '22 at 17:42
  • Did you read the duplicate targets? – Bergi Oct 09 '22 at 17:47
  • duplicate targets? what do you mean – Daniel Roberto Oct 09 '22 at 18:25
  • ohh i understand now what im doing wrong, i update the coede and now works, thanks – Daniel Roberto Oct 09 '22 at 18:32

0 Answers0