最近接觸了 nestjs 肘习,發(fā)現(xiàn)這個項目也用到依賴注入染服。
和公司現(xiàn)在運行的老項目很像扑庞。
公司的老項目
主要由 zazeninjector + koa + typeorm 組成
通過裝飾器 autoinject 進行裝飾
// @autoinject(name=account_service)
export function account_service(
u:IGlobal.Util,
) : IAccount.AccountService {
}
比如 在 account_facade 用到获黔,account_service:IAccount.AccountService
則直接作為 account_facade
這個方法的參數(shù)即可
// @autoinject(name=account_facade)
export function account_facade(
u:IGlobal.Util,
user_token_service:IUserToken.UserTokenService,
account_service:IAccount.AccountService,
platform_account_core_service:IPlatformAccount.CoreService,
) : IAccount.Facade {}
熟悉 java 的人看起來列荔,會感覺就像 spring boot 那一套,但并不是完全像
nestjs
相比公司老項目肾请,nestjs 相對更為智能留搔,創(chuàng)建新的模塊也更為方便些。
初始化 & 運行
初始化新項目
nest new project_name
會出現(xiàn)如下文件及選擇
CREATE nest-demo/.eslintrc.js (631 bytes)
CREATE nest-demo/.prettierrc (51 bytes)
CREATE nest-demo/README.md (3339 bytes)
CREATE nest-demo/nest-cli.json (64 bytes)
CREATE nest-demo/package.json (1965 bytes)
CREATE nest-demo/tsconfig.build.json (97 bytes)
CREATE nest-demo/tsconfig.json (546 bytes)
CREATE nest-demo/src/app.controller.spec.ts (617 bytes)
CREATE nest-demo/src/app.controller.ts (274 bytes)
CREATE nest-demo/src/app.module.ts (249 bytes)
CREATE nest-demo/src/app.service.ts (142 bytes)
CREATE nest-demo/src/main.ts (208 bytes)
CREATE nest-demo/test/app.e2e-spec.ts (630 bytes)
CREATE nest-demo/test/jest-e2e.json (183 bytes)
? Which package manager would you ?? to use? (Use arrow keys)
? npm
yarn
pnpm
包管理工具具體用哪個就看個人習(xí)慣了
啟動項目
? codemao cd nest-demo
? nest-demo git:(master) ? yarn run start
yarn run v1.22.10
訪問
http://localhost:3000/ 會出現(xiàn) Hello World!
nest 模塊初始目錄
image.png
生成的代碼
- app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
- app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
- 模塊裝載
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- 啟動文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
nestjs 還提供了很多功能铛铁。會一點點了解隔显。雖然不大可能用于公司現(xiàn)在的項目了。但是后續(xù)了解nestjs 的實現(xiàn)饵逐,玩一玩還是可以的