Tip - Extract body from multipart formdata

Allow for a request containing both files and data.

To be able to send both files and data in the same request of type multipart formdata, for example to create a product and upload its images in the same route, we can create an Interceptor. It is inspired by the Aspect Oriented Programming, and possesses interesting capabilities.

This NestJS docarrow-up-right better explains about the Interceptor.

For instance, one could be used to obtain the text from a field in a request of type multipart formdata, then convert it to JSON and finally set its value to the body.

nest g itc files/interceptors/body
@Injectable()
export class BodyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    const request = context.switchToHttp().getRequest<Request>();

    try {
      const body = JSON.parse(request.body.body);
      request.body = body;
    } catch (error) {
      if (error instanceof SyntaxError) {
        throw new BadRequestException(error.message);
      }
      throw error;
    }

    return next.handle();
  }
}
circle-info

Note the following:

  • By putting the JSON.parse() call inside a try/catch statement this way, we can ensure that, in case of invalid syntax, the thrown exception will be similar to Nest

  • We are expecting a SyntaxError, so we check if the error is an instanceof it, which also types the error accordingly

Thanks to Matt Pocock for his insight in this lessonarrow-up-right, from his course Total TypeScript.

Then, the BodyInterceptor may be used after the FileInterceptor, like this for example:

With this, the extraction of the @Body() and DTO validation will work properly.

Commit - Interceptor to extract body from multipart formdata

Last updated