如何为Nest JS中的Swagger创建动态响应模型
我创建了一个API,该API正在返回所选用户数据的字段。
用户模型:
@Exclude()
@Entity('users')
export class User extends Timestampable {
@ApiProperty()
@PrimaryGeneratedColumn()
id: number;
@ApiProperty()
@Expose({ groups: ['create', 'profile'] })
@Column({ unique: true })
email: string;
@ApiProperty()
@Expose({ groups: ['create'] })
@Column()
password: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
firstName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
lastName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
paternalName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
phone: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true, type: 'enum', enum: UserGender })
gender: UserGender;
}
在控制器内部,我只是返回:
return instanceToPlain(user, {
groups: ['profile'],
});
此处将仅返回具有配置文件组的用户字段。
一切正常。但是对于我使用的Swagger文档:
{
schema: {shows
$ref: getSchemaPath(User),
},
}
在文档中,它显示了用户的所有字段。
我如何仅显示特定组中的字段?
其中一种选项创建了2种不同的DTO并使用它们,但是我认为该解决方案不是那么好。
I created an API which is returning selected fields of user data.
User model:
@Exclude()
@Entity('users')
export class User extends Timestampable {
@ApiProperty()
@PrimaryGeneratedColumn()
id: number;
@ApiProperty()
@Expose({ groups: ['create', 'profile'] })
@Column({ unique: true })
email: string;
@ApiProperty()
@Expose({ groups: ['create'] })
@Column()
password: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
firstName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
lastName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
paternalName: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true })
phone: string;
@ApiProperty()
@Expose({ groups: ['profile'] })
@Column({ nullable: true, type: 'enum', enum: UserGender })
gender: UserGender;
}
Inside the controller, I just return:
return instanceToPlain(user, {
groups: ['profile'],
});
here will be returned only the fields of the user which have a profile group.
Everything working properly. But for swagger documentation I used:
{
schema: {shows
$ref: getSchemaPath(User),
},
}
and in the documentation, it shows all fields of the user.
How can I show only fields from the particular group?
One of the options create 2 different DTOs and use them but that solution in my opinion is not that good.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论