node.js - NestJS:用户管理处理不同类型的用户
问题描述
我目前正在开发一个 REST 用户服务,它应该能够存储 3 种类型的用户(管理员、测试员、客户)。我的数据库模式是建立在“每类表”策略的基础上的。所以我有一个超级表(用户),其中包含一般数据,如 id、firstName、lastName、email、password 和 userType。例如,tester 表有额外的字段,比如 rating,它的主键也是 users 表的外键。
我已经为一般用户创建了一个 DTO,并扩展了与表相对应的 DTO,这些表在路由中作为有效负载请求。是否可以在同一路由中处理不同的可能用户(POST:“/users”),或者我是否需要使用“/users/admins”、“/users/testers”和“/users/”等路由单独处理它们顾客”?
1.方法
Swagger 无法处理多个接口。
createUser(
@Body() createUserDto: CreateAdminDto | CreateTesterDto | CreateCustomerDto
) {
if (createUserDto.type === UserType.ADMIN) {
//call userService to create admin -> cast DTO to adminInterface
return 'admin';
} else if (createUserDto.type === UserType.TESTER) {
//call userService to create tester -> cast DTO to testerInterface
return 'tester';
} else if (createUserDto.type === UserType.CUSTOMER) {
//call userService to create customer -> cast DTO to customerInterface
return 'customer';
}
}
2. 方法
我已经使用 userData 属性扩展了 CreateUserDto,其中包含特定于类型的数据。使用 Swaggers oneOf
,您可以展示不同的可能性。也更容易处理。根数据进入用户表,嵌套的用户数据进入其对应的表。
import { UserType } from '../models/user';
import { CreateAdminDto } from './create-admin.dto';
import { CreateCustomerDto } from './create-customer.dto';
import { CreateTesterDto } from './create-tester.dto';
@ApiExtraModels(CreateAdminDto, CreateTesterDto, CreateCustomerDto)
export class CreateUserDtoNew {
@ApiProperty()
firstName: string;
@ApiProperty()
lastName: string;
@ApiProperty()
email: string;
@ApiProperty()
password: string;
@ApiProperty()
type: UserType;
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(CreateAdminDto) },
{ $ref: getSchemaPath(CreateTesterDto) },
{ $ref: getSchemaPath(CreateCustomerDto) }
]
})
userData: CreateCustomerDto | CreateTesterDto | CreateCustomerDto;
}
解决方案
推荐阅读
- php - 我必须在 Javascript 中调用 php 变量但在字符串中
- c# - 如何打印随机数的总和?C#
- javascript - 如何加速 SVG 变形
- android - Kotlin-android:未解决的参考
- r - 在 R 中添加包含 tibble 特定列的缺失值的列
- vue.js - Vue Formulate 的单元测试没有看到错误
- android - 配置项目时出现问题:react-native-reanimated
- python - cv2.dnn_Net.forward() 函数究竟返回什么?
- list - 如何对两个列表的元素求和。哈斯克尔
- json - 尝试在 Flutter 中以 List 形式从 API 获取数据时发现错误