返回

1. 自动验证

前端

Nestjs最实用的5个最佳实践(教程篇5):自动验证、序列化和异常处理

使用class-validator库可以轻松实现自动验证。安装库后,使用@Validate()装饰器标记要验证的属性,并使用ValidationPipe管道验证请求。

例如:

import { IsString, IsNotEmpty } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @IsNotEmpty()
  username: string;

  @IsString()
  @IsNotEmpty()
  password: string;
}

Nestjs内置了序列化支持,使用@Exclude()@Expose()装饰器控制对象的序列化和反序列化。

例如:

import { Expose, Exclude } from 'class-transformer';

export class UserDto {
  @Expose()
  username: string;

  @Exclude()
  password: string;
}

使用@Catch()装饰器处理异常。它可以拦截特定类型的异常,并提供自定义响应。

例如:

import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { HttpException } from '@nestjs/core';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      error: exception.message,
    });
  }
}

Nestjs提供了命令行界面(CLI)工具,用于创建、生成和运行应用程序。它可以通过nest命令访问。

例如:

nest generate controller users

模块是Nestjs应用程序的基本构建块。它们允许您将应用程序分解为可重用和可维护的组件。

例如:

import { Module } from '@nestjs/common';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}