代码生成器
youlai-nest 提供代码生成工具,快速生成 CRUD 代码。
使用方式
1. 运行生成器
bash
# 交互式生成
pnpm run gen
# 指定表名生成
pnpm run gen:user --table=sys_user2. 配置模板
配置文件 codegen/config.yaml:
yaml
# 数据库连接
database:
host: localhost
port: 3306
username: root
password: 123456
database: youlai_admin
# 生成配置
output:
baseDir: src/modules
override: false # 是否覆盖已有文件
# 模板配置
template:
entity: templates/entity.ts.hbs
service: templates/service.ts.hbs
controller: templates/controller.ts.hbs
dto: templates/dto.ts.hbs3. 生成的文件结构
src/modules/user/
├── user.entity.ts # 实体类
├── user.service.ts # 服务层
├── user.controller.ts # 控制器
├── user.dto.ts # DTO 定义
└── user.module.ts # 模块注册生成的实体示例
typescript
// user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity('sys_user')
export class User {
@PrimaryGeneratedColumn({ type: 'bigint' })
id: number;
@Column({ length: 50, comment: '用户名' })
username: string;
@Column({ length: 100, comment: '昵称' })
nickname: string;
@Column({ name: 'dept_id', type: 'bigint', comment: '部门ID' })
deptId: number;
@Column({ name: 'create_time', type: 'datetime', comment: '创建时间' })
createTime: Date;
@Column({ name: 'update_time', type: 'datetime', comment: '更新时间' })
updateTime: Date;
}自定义模板
模板使用 Handlebars 语法:
字段类型映射
| MySQL 类型 | TypeScript 类型 |
|---|---|
| bigint | number |
| varchar | string |
| text | string |
| datetime | Date |
| tinyint | number |
| decimal | number |
| json | object |
注意事项
- 生成后需手动检查字段类型和关联关系
- 权限控制需手动添加
- 复杂业务逻辑需手动实现
