NestJS小技巧01

727 阅读2分钟
by 雪隐 from https://juejin.cn/user/1433418895994094
本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可联系授权

大家好我是雪隐,请叫我雪宝,欢迎来到NodeJS框架NestJS的第一个提示和技巧系列。我将尝试提出一些鲜为人知但非常有用的提示和技巧,这将有助于使您的NestJS应用程序更加稳定和可读。

装饰器

我想我们大多数人都知道我们可以创建自己的装饰器,对吧?

但不太出名的是,您可以组合多个装饰器。这有助于整理代码,使其看起来更专业,更易于阅读。

例子

我在项目中大量使用了swagger,它提供了很多描述端点、类和属性的可能性,但过了一段时间,一个小方法或属性可能会如下所示:

@Controller()
export class AppController {
  @Get('/')
  @ApiOperation({ summary: '简单hello world' })
  @ApiOkResponse({
    type: String,
    description: '返回一个hello world',
  })
  @ApiBadRequestResponse({ description: 'bad request例子' })
  get(): string {
    return 'Hello World!';
  }
}

文档清晰可查…。但代价是什么?

对于具有一种方法的控制器,它仍然可读。但想象一下,使用相同但略有不同的装饰器的方法越来越多:

@Controller()
export class AppController {
  @Get('/')
  @ApiOperation({ summary: '简单hello world' })
  @ApiOkResponse({
    type: String,
    description: '返回一个hello world',
  })
  @ApiBadRequestResponse({ description: 'bad request例子' })
  get(): string {
    return 'Hello World!';
  }

  @Get('/number-world')
  @ApiOperation({ summary: '简单随机数' })
  @ApiOkResponse({ type: Number, description: '返回一个随机数!' })
  @ApiBadRequestResponse({ description: 'bad request例子' })
  getNumberWorld(): number {
    return Math.random();
  }
}

现在,您需要为下一个端点使用相同的修饰符来描述它的作用。这将随着每种方法呈指数增长。

appleDecorators是我们要找的。它帮助我们将多个装饰器组合成一个:

import { applyDecorators, SetMetadata, Type } from '@nestjs/common';
import {
  ApiOperation,
  ApiOkResponse,
  ApiBadRequestResponse,
} from '@nestjs/swagger';

export function SwaggerDocumentation(
  summary: string,
  okDescription: string,
  badRequestDescription: string,
  type: Type,
) {
  return applyDecorators(
    ApiOperation({ summary }),
    ApiOkResponse({ description: okDescription, type }),
    ApiBadRequestResponse({ description: badRequestDescription }),
  );
}

这将使我们的端点看起来像这样:

@Controller()
export class AppController {
  @Get('/')
  @SwaggerDocumentation(
    '简单hello world',
    '返回一个hello world',
    'bad request例子',
    String,
  )
  get(): string {
    return 'Hello World!';
  }

  @Get('/number-world')
  @SwaggerDocumentation(
    '简单随机数',
    '返回一个随机数!',
    'bad request例子',
    String,
  )
  getNumberWorld(): number {
    return Math.random();
  }
}

结论

将多个装饰器放在一个装饰器中,可以使代码看起来干净、易于阅读,只需花费最少的精力。

有关applyDecorators函数的更多信息,请参见官方文档

代码

代码