后端 - NestJS
文档
开始
bash
$ npm i -g @nestjs/cli
$ nest new ${project-name}
环境变量
- Configuration - NestJS
bash
# 安装
$ npm i @nestjs/config
- 新建
.env.xx
文件 - 开发环境
pacakge.json
相应的script
添加NODE_ENV=xxx
json
"scripts": {
"dev": "NODE_ENV=development nest start --watch",
"build": "nest build",
"start": "node dist/src/main",
}
- 测试和线上环境
bash
# .env.test 文件
NODE_ENV=test
# docker-compose.yml 文件
env_file:
- .env.test
项目中使用
ts
// 加载
import { ConfigModule } from '@nestjs/config';
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [`.env.${process.env.NODE_ENV}`],
}),
main.ts
中使用 - NestJSTypeORM
配置中使用 - NestJS
TIP
可以不用 ConfigService
,process.env
可以拿到值
数据库
bash
# 安装
$ npm i @nestjs/typeorm typeorm mysql2
Migrations
- DataSource - TypeORM
- Migrations - TypeORM
命令
create
:生成文件,但没有指令,自己写generate
:自动生成指令
json
// package.json script
"typeorm": "typeorm-ts-node-commonjs -d ormconfig.ts",
"migration:generate": "npm run typeorm migration:generate src/migrations/migration",
"migration:run": "npm run typeorm migration:run",
TIP
dev
环境执行 migration:generate
, ormconfig.ts 拿不到环境变量的时候,去读文件。
ts
import { config } from 'dotenv'
let env = process.env
if (!env.NODE_ENV) {
const params = config({
path: `.env.dev`,
})
env = params.parsed
}
时区
服务器和数据库都使用的UTC时间
后面购买的腾讯云数据库,它的时区默认 +08:00
可以在:数据库管理
->参数设置
->time_zone
改为+00:00
WARNING
为什么后来没使用docker部署mysql,而购买?
因为服务器配置不高,部署很容易卡死,限制太低查询又很慢。
API 文档
分成 admin-docs
和 public-docs
两端文档
- Swagger - NestJS
- redoc - GitHub
- nestjs-redoc - npm 包,非官方
- 多端文档 - NestJS
TIP
deepScanRoutes: true
需要设置
功能相关
验证
- class-validator - NestJS
- Validation - NestJS
- class-validator - GitHub
- class-transformer - GitHub
bash
# 1. 都要安装
$ npm i class-validator class-transformer
# 2. main.ts 要添加
app.useGlobalPipes(new ValidationPipe())
Response字段
admin
和 public
返回不同字段
ts
// 1. main.ts
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))
// 2. entity.ts
@Expose({ groups: ['client:admin'] })
@CreateDateColumn()
create_at: Date;
// 3. controller.ts
@SerializeOptions({ groups: ['client:admin'] })
export class ActorAdminController {}
跨域
- CORS - NestJS
部署
- 使用 Docker和Docker Compose
- 使用三级域名,配置nginx.conf反向代理
- 部署 - GitHub Actions
GitHub
这边构建rsync
文件同步到服务器ssh登录
执行docker相关操作
yml
# -d:后台运行
docker-compose -f docker-compose.test.yml --env-file .env.test --compatibility up -d --build test-api
docker exec -d test-api npm run migration:run
docker image prune -f