NestJS 用TypeScript開發 nodeJS后端


NestJS




A progressive Node.js framework for building efficient and scalable server-side applications on top of TypeScript & JavaScript (ES6 / ES7 / ES8) heavily inspired by Angular

底層用 express

設計理念
這個后端框架受 Angular 啟發 , 所以業務 代碼看起來和 Angular一樣
完全基於typescript的web框架,完全oop風格

底層是 express,如果是koa,或者fastify的話,或許會比較火


2018-01-05


官網
https://nestjs.com/


Nest官方叫我們去看Angular 的依賴注入的文檔
Nest is built around the strong design pattern commonly known as Dependency Injection. There's a great article about this concept in the official Angular documentation.


根據類型注入 , 不能根據 key

公司




已經很好用了 , 但是不確定是否這么強大 :  高級的功能

官方提供的ORM
分布式微服務

官方有提供 :
命令行工具


示例代碼
https://github.com/nestjs/nest.git
E:\NestJS\nest\examples

框架源碼
https://github.com/nestjs/nest.git



components 注解相當於 Spring 的 @Service

最后在模塊里配置一下 , 相當於 Spring 的 xml 配置

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

@Module({
    controllers: [CatsController],
    components: [CatsService],
})
export class ApplicationModule {}



實踐

npm start 或者 npm run start
默認在 3000 端口
npm start

> nest-typescript-starter@1.0.0 start E:\NestJS\nest\examples\01-cats-app
> node index.js

[Nest] 12736   - 2018-1-5 09:11:29   [NestFactory] Starting Nest application...
[Nest] 12736   - 2018-1-5 09:11:29   [InstanceLoader] ApplicationModule dependencies initialized +7ms
[Nest] 12736   - 2018-1-5 09:11:29   [InstanceLoader] CatsModule dependencies initialized +2ms
[Nest] 12736   - 2018-1-5 09:11:29   [RoutesResolver] CatsController {/cats}: +29ms
[Nest] 12736   - 2018-1-5 09:11:29   [RouterExplorer] Mapped {/, POST} route +1ms
[Nest] 12736   - 2018-1-5 09:11:29   [RouterExplorer] Mapped {/, GET} route +0ms
[Nest] 12736   - 2018-1-5 09:11:29   [RouterExplorer] Mapped {/:id, GET} route +1ms
[Nest] 12736   - 2018-1-5 09:11:29   [NestApplication] Nest application successfully started +1ms

有請求路由的信息 , 比如
/cats



暫時沒數據

要發POST請求創建數據 , 角色是 admin , 不然不能添加數據
@UseGuards(RolesGuard)

然后get再獲取一次

Guards are executed after every middleware, but before pipes.

為什么要用  Guards ? 之前已經用了 middleware






項目加載順序
從左到右









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM