Skip to content

Manipulate the request body inside a custom middleware while using bodyCoercion true #1744

Open
@raphaell-roussel-greenly

Description

In our project, we wrote some custom middlewares that read data from the request. We noticed an issue when one of our endpoint returned a 500 error when trying to handle a invalid body.

Consider the following pseudo-code from inside a controller:

@Post()
@Middlewares(
  async (
    request: ExpressRequest,
    response: ExpressResponse,
    next: NextFunction,
  ) => {
    // Do something with the request body assumed to be an array
    for (const bodyElement of request.body) {
      console.log(bodyElement);
    }
    next();
  }
)
public async postMethod(
  @Body() body: string[],
): {
  // Controller logic here
}

The issue arises when sending a non-array string as a body. Body coercion will ensure we still accept a string and makes it so it is cast as an array in the controller body argument. However in the middleware, we're manipulating the raw request.body from Express (in our case) which did not go through the body coercion and is a string, not an array.

I don't know if I understood correctly the order of code execution and the middleware code might not be supposed to be called before validation. In our case, the validation happens first, that might be because of our custom TSOA generated routes file that I did not provide here.

  • Is there a way to manipulate the coerced body inside a middleware?
  • I would love to be able to use directly TSOA decorators @Body() or any other decorator inside the custom middleware to avoid manipulating the Express request object, is it something possible and/or desirable as a feature request?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions