如何使用NestJS開發(fā)Node.js應(yīng)用-創(chuàng)新互聯(lián)

這篇文章主要介紹如何使用NestJS開發(fā)Node.js應(yīng)用,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比文峰網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式文峰網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋文峰地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。

NestJS 最早在 2017.1 月立項(xiàng),2017.5 發(fā)布第一個(gè)正式版本,它是一個(gè)基于 Express,使用 TypeScript 開發(fā)的后端框架。設(shè)計(jì)之初,主要用來解決開發(fā) Node.js 應(yīng)用時(shí)的架構(gòu)問題,靈感來源于 Angular。

組件容器

如何使用NestJS開發(fā)Node.js應(yīng)用

NestJS 采用組件容器的方式,每個(gè)組件與其他組件解耦,當(dāng)一個(gè)組件依賴于另一組件時(shí),需要指定節(jié)點(diǎn)的依賴關(guān)系才能使用:

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 相似,同是使用依賴注入的設(shè)計(jì)模式開發(fā)

如何使用NestJS開發(fā)Node.js應(yīng)用

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

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

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

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

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

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

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

細(xì)?;?Middleware

在使用 Express 時(shí),我們會(huì)使用各種各樣的中間件,譬如日志服務(wù)、超時(shí)攔截,權(quán)限驗(yàn)證等。在 NestJS 中,Middleware 功能被劃分為 Middleware、Filters、Pipes、Grards、Interceptors。

例如使用 Filters,來捕獲處理應(yīng)用中拋出的錯(cuò)誤:

@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ù),使得返回?cái)?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,當(dāng)不具有 'admin' 角色時(shí),返回 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ù)驗(yàn)證

得益于class-validator 與class-transformer 對(duì)傳入?yún)?shù)的驗(yàn)證變的非常簡(jiǎn)單:

// 創(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()
 }
}

當(dāng)所傳入?yún)?shù) text 不是 string 時(shí),會(huì)出現(xiàn) 400 的錯(cuò)誤。

GraphQL

GraphQL 由 facebook 開發(fā),被認(rèn)為是革命性的 API 工具,因?yàn)樗梢宰尶蛻舳嗽谡?qǐng)求中指定希望得到的數(shù)據(jù),而不像傳統(tǒng)的 REST 那樣只能在后端預(yù)定義。

NestJS 對(duì) Apollo server 進(jìn)行了一層包裝,使得能在 NestJS 中更方便使用。

在 Express 中使用 Apollo server 時(shí):

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開發(fā)Node.js應(yīng)用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

名稱欄目:如何使用NestJS開發(fā)Node.js應(yīng)用-創(chuàng)新互聯(lián)
網(wǎng)站鏈接:http://muchs.cn/article36/psgsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、網(wǎng)站制作、動(dòng)態(tài)網(wǎng)站、手機(jī)網(wǎng)站建設(shè)、微信小程序、做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名