API with NestJS #5. Serializing the response with interceptors

JavaScript NestJS TypeScript

This entry is part 5 of 121 in the API with NestJS

Sometimes we need to perform additional operations on the outcoming data. We might not want to expose specific properties or modify the response in some other way. In this article, we look into various solutions NestJS provides us with to change the data we send in the response.

You can find the code from this series in this repository.

Serialization

The first thing to look into is the serialization. It is a process of transforming the response data before returning it to the user.

In the previous parts of this series, we’ve removed the password in the various parts of our API. A better approach would be using the class-transformer.

users/user.entity.ts

NestJS comes equipped with   that uses class-transformer under the hood. To apply the above transformation, we need to use it in our controller:

If we find ourselves adding  to a lot of controllers, we can configure it globally instead.

main.ts

The  needs the Reflector when initializing.

By default, all properties of our entities are exposed. We can change this strategy by providing additional options to the class-transformer. To do so, we need to use the   decorator.

users/user.entity.ts

 

The   decorator has more options that you might find useful. It matches the options that you can provide for the   method in the class-transformer.

The class-transformer library has quite a few useful features. Another noteworthy one is the ability to transform values. To demonstrate it, let’s create a nullable column:

Since the   is a nullable column, it is optional, its value is null until we set it. This means sending null values in the response:

The above behavior might be considered undesirable and the most straightforward way to fix it is to use the   decorator. If the value equals null, we don’t want to send in the response.

Issues with using the @Res() decorator

In the previous part of this series, we’ve used the   decorator to access the Express Response object. Thanks to that, we were able to attach cookies to the response.

Using the  decorator strips us from some advantages of using NestJS. Unfortunately, it interferes with the  . To prevent that, we can follow some advice from the creator of NestJS. If we use the   object instead of the   decorator, we don’t put NestJS into the express-specific mode.

The above is a neat little trick that we use to take advantage of the mechanisms built into NestJS while accessing the Response object directly.

Custom interceptors

Above, we use the   decorator to skip a single property if it equals null. Doing so for every nullable property does not seem like a clean approach.

Fortunately, aside from using the  , we can create our own interceptors. Interceptors can serve various purposes, and one of them is manipulating the request/response stream.

utils/excludeNull.interceptor.ts

Each interceptor needs to implement the   and, therefore, the   method. It takes two arguments:

    • it provides information about the current context,
    • it contains the   method that invokes the route handler and returns an RxJS Observable

The   method wraps the request/response stream, and we can add logic both before and after the execution of the route handler. In the above code, we invoke the route handle and modify the response.

Since there are quite a few places in the NestJS framework that make use of RxJS, the official TypeScript starter already contains it.

utils/recursivelyStripNullValues.ts

In the above function, we recursively travel the data structure and preserve values only if they differ from null. It works both for arrays and plain objects.

If you want to know more about recursion in JavaScript, check out Using recursion to traverse data structures. Execution context and the call stack
Also, every recursive function can be turned into an iterative one

Summary

In this article, we’ve looked into how we can modify the response that we send back to our users. While the most straightforward way to do so is to serialize the response with  , we can also create our own interceptor. We’ve also looked into how we can bypass the issue of using the  decorator.

Series Navigation<< API with NestJS #4. Error handling and data validationAPI with NestJS #6. Looking into dependency injection and modules >>
Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
collinsmuriuki
3 years ago

Hello, nice tutorial. Would like to add a fix to the recursivelyStripNullValues function. With the current implementation, it transforms Date objects i.e createdAt and updatedAt fields to empty objects, since the typeof these values is indeed an object.
To fix this, here is a small additional check to add to the function:

Last edited 3 years ago by collinsmuriuki
Dmytro Ben
Dmytro Ben
3 years ago

You have wrong declaration
@Transform(value => {

it should be
@Transform( ({ value }) => {

Mark
Mark
3 years ago

Great tutorial thanks.
I think it would solve some problems by explaining the Res issue before discussing putting in Exclude logic globally (i.e. Putting useGlobalInterceptors in the main file)
This stumped me for quite a while as I was testing all my end points after adding Exclude and wondering why the site fell over if I did a post or anything requiring a response

Nikunj
Nikunj
2 years ago

After using the interceptor I am not getting a response, I am getting a null object as a response. Does anyone have the same issue?

If I don’t use intercepter in the main.ts file then I working fine

Ryan Alves de Oliveira
Ryan Alves de Oliveira
11 months ago

Hello, just remembering anyone that after creating the ExcludeNullInterceptor we can remove the @Transform() decorator from ‘category’, then just remember to add the interceptor in main.ts: