目前,在我的打字稿代码(nestjs)中,我使用控制器中的 DTO 来验证进入 API 的数据,模式用作其余文件中的类型,并且除特殊情况外我不会创建接口。
我试图弄清楚我正在做的事情是否好,或者我是否应该在任何地方使用 DTO 作为类型,或者其他什么?目标是提高代码的质量。
用户集合示例:
user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
@Schema({ collection: 'users' })
export class User extends Document {
@Prop()
name: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.set('timestamps', true);
Run Code Online (Sandbox Code Playgroud)
user.dto.ts
import { IsNotEmpty, IsString, Length } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class UserDto {
@IsNotEmpty()
@IsString()
@Length(3)
@ApiProperty({ required: true })
readonly name: string;
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
async …Run Code Online (Sandbox Code Playgroud)