欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用NestJS開發(fā)Node.js應用的方法

 更新時間:2018年12月03日 10:48:38   作者:三毛丶  
這篇文章主要介紹了使用NestJS開發(fā)Node.js應用的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

NestJS 最早在 2017.1 月立項,2017.5 發(fā)布第一個正式版本,它是一個基于 Express,使用 TypeScript 開發(fā)的后端框架。設計之初,主要用來解決開發(fā) Node.js 應用時的架構問題,靈感來源于 Angular。在本文中,我將粗略介紹 NestJS 中的一些亮點。

組件容器

NestJS 采用組件容器的方式,每個組件與其他組件解耦,當一個組件依賴于另一組件時,需要指定節(jié)點的依賴關系才能使用:

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { OtherModule } from '../OtherModule';

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

依賴注入(DI)

與 Angular 相似,同是使用依賴注入的設計模式開發(fā)

當使用某個對象時,DI 容器已經(jīng)幫你創(chuàng)建,無需手動實例化,來達到解耦目的:

// 創(chuàng)建一個服務
@Inject()
export class TestService {
 public find() {
 return 'hello world';
 }
}

// 創(chuàng)建一個 controller
@Controller()
export class TestController {
 controller(
 private readonly testService: TestService
 ) {}
 
 @Get()
 public findInfo() {
 return this.testService.find()
 }
}

為了能讓 TestController 使用 TestService 服務,只需要在創(chuàng)建 module 時,作為 provider 寫入即可:

@Module({
 controllers: [TestController],
 providers: [TestService],
})
export class TestModule {}

當然,你可以把任意一個帶 @Inject() 的類,注入到 module 中,供此 module 的 Controller 或者 Service 使用。

背后的實現(xiàn)基于 Decorator + Reflect Metadata,詳情可以查看深入理解 TypeScript - Reflect Metadata 。

細粒化的 Middleware

在使用 Express 時,我們會使用各種各樣的中間件,譬如日志服務、超時攔截,權限驗證等。在 NestJS 中,Middleware 功能被劃分為 Middleware、Filters、Pipes、Grards、Interceptors。

例如使用 Filters,來捕獲處理應用中拋出的錯誤:

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

 // 一些其他做的事情,如使用日志

 response
  .status(status)
  .json({
  statusCode: status,
  timestamp: new Date().toISOString(),
  path: request.url,
  });
 }
}

使用 interceptor,攔截 response 數(shù)據(jù),使得返回數(shù)據(jù)格式是 { data: T } 的形式:

import { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
 data: T;
}

@Injectable()
export class TransformInterceptor<T>
 implements NestInterceptor<T, Response<T>> {
 intercept(
 context: ExecutionContext,
 call$: Observable<T>,
 ): Observable<Response<T>> {
 return call$.pipe(map(data => ({ data })));
 }
}

使用 Guards,當不具有 'admin' 角色時,返回 401:

import { ReflectMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles);

@Post()
@Roles('admin')
async create(@Body() createCatDto: CreateCatDto) {
 this.catsService.create(createCatDto);
}

數(shù)據(jù)驗證

得益于class-validatorclass-transformer 對傳入?yún)?shù)的驗證變的非常簡單:

// 創(chuàng)建 Dto
export class ContentDto {
 @IsString()
 text: string
}

@Controller()
export class TestController {
 controller(
 private readonly testService: TestService
 ) {}
 
 @Get()
 public findInfo(
 @Param() param: ContentDto  // 使用
 ) {
 return this.testService.find()
 }
}

當所傳入?yún)?shù) text 不是 string 時,會出現(xiàn) 400 的錯誤。

GraphQL

GraphQL 由 facebook 開發(fā),被認為是革命性的 API 工具,因為它可以讓客戶端在請求中指定希望得到的數(shù)據(jù),而不像傳統(tǒng)的 REST 那樣只能在后端預定義。

NestJS 對 Apollo server 進行了一層包裝,使得能在 NestJS 中更方便使用。

在 Express 中使用 Apollo server 時:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
 type Query {
 hello: String
 }
`;

// Provide resolver functions for your schema fields
const resolvers = {
 Query: {
 hello: () => 'Hello world!',
 },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

const port = 4000;

app.listen({ port }, () =>
 console.log(`Server ready at http://localhost:${port}${server.graphqlPath}`),
);

在 NestJS 中使用它:

// test.graphql
type Query {
 hello: string;
}


// test.resolver.ts
@Resolver()
export class {
 @Query()
 public hello() {
 return 'Hello wolrd';
 }
}

使用 Decorator 的方式,看起來也更 TypeScript 。

其他

除上述一些列舉外,NestJS 實現(xiàn)微服務開發(fā)、配合 TypeORM 、以及 Prisma 等特點,在這里就不展開了。

參考

深入理解 TypeScript - Reflect Metadata

Egg VS NestJS

NestJS 官網(wǎng)

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 淺談使用nodejs搭建web服務器的過程

    淺談使用nodejs搭建web服務器的過程

    這篇文章主要介紹了淺談使用nodejs搭建web服務器的過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • Node.js中Express框架的使用教程詳解

    Node.js中Express框架的使用教程詳解

    這篇文章主要為大家詳細介紹了Node.js中的開發(fā)框架Express,利用Express框架可以快速的進行Web后端開發(fā),感興趣的小伙伴可以了解一下
    2022-04-04
  • node.js中的console.timeEnd方法使用說明

    node.js中的console.timeEnd方法使用說明

    這篇文章主要介紹了node.js中的console.timeEnd方法使用說明,本文介紹了console.timeEnd的方法說明、語法、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • nvm安裝方法以及安裝后node不能使用解決

    nvm安裝方法以及安裝后node不能使用解決

    在我們的日常開發(fā)中經(jīng)常會遇到這種情況,手上有好幾個項目,每個項目的需求不同,進而不同項目必須依賴不同版的NodeJS運行環(huán)境,nvm應運而生,這篇文章主要給大家介紹了關于nvm安裝方法以及安裝后node不能使用解決的相關資料,需要的朋友可以參考下
    2023-04-04
  • npx的使用及原理分析

    npx的使用及原理分析

    這篇文章主要介紹了npx的使用及原理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Nodejs中調(diào)用系統(tǒng)命令、Shell腳本和Python腳本的方法和實例

    Nodejs中調(diào)用系統(tǒng)命令、Shell腳本和Python腳本的方法和實例

    這篇文章主要介紹了Nodejs中調(diào)用系統(tǒng)命令、Shell腳本和Python腳本的方法和實例,本文給出了利用子進程調(diào)用系統(tǒng)命令、執(zhí)行系統(tǒng)命令、調(diào)用傳參數(shù)的shell腳本、調(diào)用python腳本的例子,需要的朋友可以參考下
    2015-01-01
  • 深入理解Node內(nèi)建模塊和對象

    深入理解Node內(nèi)建模塊和對象

    在node核心中有些內(nèi)建模塊,使用這些模塊可以操作系統(tǒng),文件和網(wǎng)絡,這篇文章主要介紹了深入理解Node內(nèi)建模塊和對象,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • node.js中的fs.utimes方法使用說明

    node.js中的fs.utimes方法使用說明

    這篇文章主要介紹了node.js中的fs.utimes方法使用說明,本文介紹了fs.utimes的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • node.js平臺下的mysql數(shù)據(jù)庫配置及連接

    node.js平臺下的mysql數(shù)據(jù)庫配置及連接

    本文主要介紹了node.js平臺下的mysql數(shù)據(jù)庫配置及連接的相關知識。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-03-03
  • Node.js基礎入門之緩存區(qū)與文件操作詳解

    Node.js基礎入門之緩存區(qū)與文件操作詳解

    Node.js是一個基于Chrome?V8引擎的JavaScript運行時。類似于Java中的JRE,.Net中的CLR。本文將詳細為大家介紹Node.js中的緩存區(qū)與文件操作,感興趣的可以了解一下
    2022-03-03

最新評論