首页 > 解决方案 > 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;
}

标签: node.jsrestexpressbackendnestjs

解决方案


推荐阅读