nest.js 初探
2021-10-04 本文已影响0人
ithankzc
最近接触了 nestjs ,发现这个项目也用到依赖注入。
和公司现在运行的老项目很像。
公司的老项目
主要由 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
这个方法的参数即可
// @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 相对更为智能,创建新的模块也更为方便些。
初始化 & 运行
初始化新项目
nest new project_name
会出现如下文件及选择
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
包管理工具具体用哪个就看个人习惯了
启动项目
➜ codemao cd nest-demo
➜ nest-demo git:(master) ✗ yarn run start
yarn run v1.22.10
访问
http://localhost:3000/ 会出现 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 还提供了很多功能。会一点点了解。虽然不大可能用于公司现在的项目了。但是后续了解nestjs 的实现,玩一玩还是可以的