Nest 個(gè)人學(xué)習(xí)整理

一、Controller

  • 控制器的目的是接收應(yīng)用的特定請(qǐng)求
import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

二、Provider

  • 控制器應(yīng)處理 HTTP 請(qǐng)求并將更復(fù)雜的任務(wù)委托給 providers。Providers 是純粹的 JavaScript 類,在其類聲明之前帶有 @Injectable()裝飾器。
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

三、Module

  • 每個(gè) Nest 應(yīng)用程序至少有一個(gè)模塊,即根模塊。
    在大多數(shù)情況下,您將擁有多個(gè)模塊,每個(gè)模塊都有一組緊密相關(guān)的功能。
    • providers 由 Nest 注入器實(shí)例化的提供者,并且可以至少在整個(gè)模塊中共享
    • controllers 必須創(chuàng)建的一組控制器
    • imports 導(dǎo)入模塊的列表,這些模塊導(dǎo)出了此模塊中所需提供者
    • exports 由本模塊提供并應(yīng)在其他模塊中可用的提供者的子集。
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

四、中間件

  • 中間件是在路由處理程序,之前,調(diào)用的函數(shù)
  • 中間件不能在 @Module() 裝飾器中列出。我們必須使用模塊類的 configure() 方法來(lái)設(shè)置它們。包含中間件的模塊必須實(shí)現(xiàn) NestModule 接口。
// 聲明
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Request...');
    next();
  }
}
1.局部 應(yīng)用中間件
// 應(yīng)用中間件
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('cats');
  }
}
2.局部 函數(shù)式中間件
// 函數(shù)式中間件
export function logger(req, res, next) {
  console.log(`Request...`);
  next();
};
consumer
  .apply(logger)
  .forRoutes(CatsController);

3.全局中間件
// 全局中間件
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);

五、過(guò)濾器

  • 所有異常過(guò)濾器都應(yīng)該實(shí)現(xiàn)通用的 ExceptionFilter<T> 接口。它需要你使用有效簽名提供 catch(exception: T, host: ArgumentsHost)方法。T 表示異常的類型。
// 異常過(guò)濾器
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

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

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}
1.局部過(guò)濾器
// 局部過(guò)濾器 @UseFilters()
@Post()
@UseFilters(new HttpExceptionFilter())
async create(@Body() createCatDto: CreateCatDto) {
  throw new ForbiddenException();
}
2.全局過(guò)濾器
// 全局過(guò)濾器 useGlobalFilters
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));

  await app.listen(3000);
}
bootstrap();

六、管道

  • 必須提供 transform() 方法
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class ValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return value;
  }
}
  • 綁定 @UsePipes()
@Post()
@UsePipes(new JoiValidationPipe(createCatSchema))
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

7、守衛(wèi)

  • 每個(gè)守衛(wèi)必須實(shí)現(xiàn)一個(gè)canActivate()函數(shù)
// 聲明
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    return validateRequest(request);
  }
}
// 綁定 @UseGuards()
@Controller('cats')
@UseGuards(RolesGuard)
export class CatsController {}

八、攔截器

  • 每個(gè)攔截器都有 intercept() 方法,它接收2個(gè)參數(shù)。第一個(gè)是 ExecutionContext 實(shí)例(與守衛(wèi)完全相同的對(duì)象)。
// 聲明
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Before...');
    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}
// 綁定
@UseInterceptors(LoggingInterceptor)
export class CatsController {}

最后

文章為了方便個(gè)人學(xué)習(xí)梳理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容