# Tip - Extract body from multipart formdata

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 doc](https://docs.nestjs.com/interceptors) 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 <mark style="color:blue;">`body`</mark>.

```sh
nest g itc files/interceptors/body
```

```typescript
@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();
  }
}
```

{% hint style="info" %}
Note the following:

* By putting the <mark style="color:blue;">`JSON.parse()`</mark> 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 <mark style="color:blue;">`SyntaxError`</mark>, so we check if the <mark style="color:blue;">`error`</mark> is an <mark style="color:blue;">`instanceof`</mark> it, which also types the <mark style="color:blue;">`error`</mark> accordingly
  {% endhint %}

> Thanks to **Matt Pocock** for his insight in [this lesson](https://www.totaltypescript.com/tutorials/beginners-typescript/beginner-s-typescript-section/typing-errors-in-a-try-catch/solution), from his course **Total TypeScript**.

Then, the <mark style="color:blue;">`BodyInterceptor`</mark> may be used after the <mark style="color:blue;">`FileInterceptor`</mark>, like this for example:

```typescript
@UseInterceptors(FileInterceptor('file'), BodyInterceptor)
```

With this, the extraction of the <mark style="color:blue;">`@Body()`</mark> and DTO validation will work properly.

<mark style="color:green;">**Commit**</mark> - Interceptor to extract body from multipart formdata
