最近在学Nestjs,其中能过nest g src test
生成了下面的各种配置,
但是呢dto和entity中几乎没什么东西。
但是我看如下别人的项目中的entity里面的数据,可以判定是用什么方法生成的?所以怎么来生成entity和dto里的结构数据?
最近在学Nestjs,其中能过nest g src test
生成了下面的各种配置,
但是呢dto和entity中几乎没什么东西。
但是我看如下别人的项目中的entity里面的数据,可以判定是用什么方法生成的?所以怎么来生成entity和dto里的结构数据?
我会以经验丰富的NestJS开发者的身份为您解答:
推荐三种主流解决方案:
TypeORM逆向工程(推荐)
npm install -g typeorm-model-generator
typeorm-model-generator -h <host> -d <database> -u <user> -x <password> -e mysql -o src/entities
这会根据现有数据库结构自动生成带有装饰器的Entity类
使用CLI代码生成器(需手动补充)
nest g resource users
生成基础框架后,通过TypeORM装饰器手动补充字段:
// user.entity.ts
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 50 })
username: string;
@Column({ type: 'datetime' })
created_at: Date;
}
// create-user.dto.ts
export class CreateUserDto {
@IsString()
@MaxLength(50)
username: string;
}
Schema-First自动生成(需GraphQL)
安装插件:
npm install @nestjs/graphql @nestjs/apollo class-validator
配置自动生成(schema.gql会自动生成TS类型):
// graphql.config.ts
const config: GqlConfigService = {
autoSchemaFile: true,
transformSchema: schema => autoSchemaFile(schema),
buildSchemaOptions: {
numberScalarMode: 'integer',
}
}
最佳实践建议:
typeorm-model-generator
生成基础Entityclass-validator
扩展DTO验证规则配置全局验证管道:
// main.ts
app.useGlobalPipes(
new ValidationPipe({
transform: true,
forbidNonWhitelisted: true
})
);
常见字段映射参考表:
MySQL类型 | TypeORM装饰器 | DTO装饰器 |
---|---|---|
INT | @Column({ type: 'int' }) | @IsNumber() |
VARCHAR | @Column({ length: 255 }) | @IsString() @MaxLength(255) |
DATETIME | @Column({ type: 'datetime' }) | @IsDateString() |
TINYINT(1) | @Column({ type: 'boolean' }) | @IsBoolean() |
TEXT | @Column({ type: 'text' }) | @IsString() |
注意事项:
synchronize: true
entity是数据库里面的字段,在连接数据库的时候配置好

synchronize
,这里写好就会自动在数据库里面创建表和字段dto主要数据结构和数据校验
