为什么选 NestJS

NestJS 是目前 Node.js 生态里架构最完善的后端框架,借鉴了 Angular 的模块化思想,天然支持 TypeScript,有完整的 IoC/DI 容器。

项目初始化

npm install -g @nestjs/cli
nest new my-api
cd my-api
npm install @nestjs/typeorm typeorm pg

配置 PostgreSQL 连接

TypeOrmModule.forRoot({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  entities: [__dirname + '/**/*.entity{.ts,.js}'],
  synchronize: false,
})

定义 Entity

@Entity('articles')
export class Article {
  @PrimaryGeneratedColumn() id: number;
  @Column({ unique: true }) slug: string;
  @Column() title: string;
  @Column({ type: 'text' }) content: string;
  @CreateDateColumn() createdAt: Date;
}

JWT 鉴权

npm install @nestjs/jwt @nestjs/passport passport-jwt

实现 JwtStrategy,配合 @UseGuards(AuthGuard('jwt')) 装饰器保护路由。