API with NestJS #5. Serializing the response with interceptors

栏目: IT技术 · 发布时间: 4年前

内容简介: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 w

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

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { Exclude } from 'class-transformer';
 
@Entity()
class User {
  @PrimaryGeneratedColumn()
  public id?: number;
 
  @Column({ unique: true })
  public email: string;
 
  @Column()
  public name: string;
 
  @Column()
  @Exclude()
  public password: string;
}
 
export default User;

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

@Controller('authentication')
@UseInterceptors(ClassSerializerInterceptor)
class AuthenticationController

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

main.ts

import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cookieParser from 'cookie-parser';
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalInterceptors(new ClassSerializerInterceptor(
    app.get(Reflector))
  );
  app.use(cookieParser());
  await app.listen(3000);
}
bootstrap();

The ClassSerializerInterceptor 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 @ SerializeOptions ( ) decorator.

@Controller('authentication')
@SerializeOptions({
  strategy: 'excludeAll'
})
export class AuthenticationController

users/user.entity.ts

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { Expose } from 'class-transformer';
 
@Entity()
class User {
  @PrimaryGeneratedColumn()
  public id?: number;
 
  @Column({ unique: true })
  @Expose()
  public email: string;
 
  @Column()
  @Expose()
  public name: string;
 
  @Column()
  public password: string;
}
 
export default User;

API with NestJS #5. Serializing the response with interceptors

The @ SerializeOptions ( ) decorator has more options that you might find useful. It matches the options that you can provide for the  classToPlain 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:

@Entity()
class Post {
  // ...
 
  @Column({ nullable: true })
  public category?: string;
}

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

API with NestJS #5. Serializing the response with interceptors

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

@Column({ nullable: true })
@Transform(value => {
  if (value !== null) {
    return value;
  }
})
public category?: string;

Issues with using the @ Res ( ) decorator

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

@HttpCode(200)
@UseGuards(LocalAuthenticationGuard)
@Post('log-in')
async logIn(@Req() request: RequestWithUser, @Res() response: Response) {
  const {user} = request;
  const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
  response.setHeader('Set-Cookie', cookie);
  user.password = undefined;
  return response.send(user);
}

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

@HttpCode(200)
@UseGuards(LocalAuthenticationGuard)
@Post('log-in')
async logIn(@Req() request: RequestWithUser) {
  const {user} = request;
  const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
  request.res.setHeader('Set-Cookie', cookie);
  return user;
}

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 @ Transform 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 ClassSerializerInterceptor , 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

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import recursivelyStripNullValues from './recursivelyStripNullValues';
 
@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next
      .handle()
      .pipe(map(value => recursivelyStripNullValues(value)));
  }
}

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

  1. ExecutionContext
    • it provides information about the current context,
  2. CallHandler
    • it contains the  handle  method that invokes the route handler and returns an RxJS Observable

The intercept 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

function recursivelyStripNullValues(value: unknown): unknown {
  if (Array.isArray(value)) {
    return value.map(recursivelyStripNullValues);
  }
  if (value !== null && typeof value === 'object') {
    return Object.fromEntries(
      Object.entries(value).map(([key, value]) => [key, recursivelyStripNullValues(value)])
    );
  }
  if (value !== null) {
    return value;
  }
}

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 ClassSerializerInterceptor , we can also create our own interceptor. We’ve also looked into how we can bypass the issue of using the @ Res ( ) decorator.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

鲜活的数据

鲜活的数据

[美] Nathan Yau / 向怡宁 / 人民邮电出版社 / 2012-10-1 / 69.00元

在生活中,数据几乎无处不在,任我们取用。然而,同样的数据给人的感觉可能会千差万别:或冰冷枯燥,让人望而生畏、百思不解其意;或生动有趣,让人一目了然、豁然开朗。为了达到后一种效果,我们需要采用一种特别的方式来展示数据,来解释、分析和应用它。这就是数据可视化技术。Nath an Yau是这一创新领域的先锋。在本书中,他根据数据可视化的工作流程,先后介绍了如何获取数据,将数据格式化,用可视化工具(如R)......一起来看看 《鲜活的数据》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码