API with NestJS #5. Serializing the response with interceptors

JavaScript NestJS TypeScript

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
0 Comments
Inline Feedbacks
View all comments