新建NestJS项目

官网
https://docs.nestjs.com/controllers
参考
https://user-cube.medium.com/build-a-rest-api-from-scratch-using-nestjs-37bfcf81cc5f

注意点:
1:NestJS可以选择两种不同的Http平台,express和fastify
https://docs.nestjs.com/first-steps#platform

2:Controller的通配符
@Get('ab*cd') //星号代表通配符
findAll() {
return 'This route uses a wildcard';
}

3:返回Response时增加header
https://docs.nestjs.com/controllers#headers

4:异常处理/exception filter
GlobalFilter / controller级别的filter / action级别的filter
https://docs.nestjs.com/exception-filters

5:配置
configuration.ts

app.module.ts

main.ts

安装
//全局安装nest cli
npm i -g @nestjs/cli
//clone模板项目
git clone https://github.com/nestjs/typescript-starter.git ebd.front.bff

打开.prettierrc,增加规则:"endOfLine":"auto"

nest g controller items
cd到对应文件夹下:
nest g interface items
新建Services文件夹,cd到该文件夹
nest g service items

//配置
npm install @nestjs/config --save
//日志
npm install --save nest-winston winston
//实现winston按日记录
npm install winston-daily-rotate-file

最终的app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HeaderModule } from './header/header.module';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import 'winston-daily-rotate-file';

@Module({
  imports: [
    HeaderModule,
    WinstonModule.forRoot({
      transports: [
        new winston.transports.DailyRotateFile({
          dirname: 'logs',
          filename: 'application-%DATE%.log',
          datePattern: 'YYYY-MM-DD-HH',
          zippedArchive: true,
          maxSize: '20m',
          maxFiles: '14d',
          format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.json(),
          ),
        }),
      ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Controller文件


import { Controller, Get, Param, Inject } from '@nestjs/common';
import { Menu } from './interfaces';
import { MenuService } from './services/menu/menu.service';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';

@Controller('header')
export class HeaderController {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
    private readonly menuService: MenuService,
  ) {}

  @Get('menu')
  async getMenus(): Promise<Menu[]> {
    const menus = await this.menuService.getAllMenus();
    this.logger.info(`header/menu -> ${JSON.stringify(menus)}`);
    return menus;
  }

  @Get()
  findAll(): string {
    return 'All Items';
  }
  @Get(':id')
  findById(@Param() param): string {
    return param.id;
  }
}

最后附上源码:
https://github.com/992990831/NestJS.git

posted @ 2021-01-09 23:06  老胡Andy  阅读(703)  评论(0编辑  收藏  举报