1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關(guān)咨詢(xún)
      選擇下列產(chǎn)品馬上在線(xiàn)溝通
      服務(wù)時(shí)間:8:30-17:00
      你可能遇到了下面的問(wèn)題
      關(guān)閉右側(cè)工具欄

      新聞中心

      這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
      如何使用NestJS開(kāi)發(fā)Node.js應(yīng)用

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

      創(chuàng)新互聯(lián)建站專(zhuān)注于西陵企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè),商城開(kāi)發(fā)。西陵網(wǎng)站建設(shè)公司,為西陵等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站制作,專(zhuān)業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專(zhuān)業(yè)和態(tài)度為您提供的服務(wù)

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

      組件容器

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

      NestJS 采用組件容器的方式,每個(gè)組件與其他組件解耦,當(dāng)一個(gè)組件依賴(lài)于另一組件時(shí),需要指定節(jié)點(diǎn)的依賴(lài)關(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 {}

      依賴(lài)注入(DI)

      與 Angular 相似,同是使用依賴(lài)注入的設(shè)計(jì)模式開(kāi)發(fā)

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

      當(dāng)使用某個(gè)對(duì)象時(shí),DI 容器已經(jīng)幫你創(chuàng)建,無(wú)需手動(dòng)實(shí)例化,來(lái)達(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 寫(xiě)入即可:

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

      當(dāng)然,你可以把任意一個(gè)帶 @Inject() 的類(lèi),注入到 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,來(lái)捕獲處理應(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 {
       data: T;
      }
      
      @Injectable()
      export class TransformInterceptor
       implements NestInterceptor> {
       intercept(
       context: ExecutionContext,
       call$: Observable,
       ): Observable> {
       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 開(kāi)發(fā),被認(rèn)為是革命性的 API 工具,因?yàn)樗梢宰尶蛻?hù)端在請(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 的方式,看起來(lái)也更 TypeScript

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


      當(dāng)前標(biāo)題:如何使用NestJS開(kāi)發(fā)Node.js應(yīng)用
      文章網(wǎng)址:http://www.ef60e0e.cn/article/jshhoc.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        茌平县| 山东省| 墨江| 阿拉善左旗| 章丘市| 苏尼特右旗| 屏边| 隆安县| 卓资县| 崇仁县| 吴堡县| 枞阳县| 子洲县| 濉溪县| 满洲里市| 乐平市| 茂名市| 旅游| 天津市| 海安县| 宕昌县| 普兰店市| 苗栗县| 佛学| 张家港市| 洪江市| 杭锦旗| 东安县| 三江| 岗巴县| 新乡市| 绥德县| 泽库县| 平陆县| 民勤县| 洛阳市| 南部县| 镇康县| 辽中县| 鄯善县| 和田市|