0

I wanna avoid write more controllers as same. So passing DTO class as generic type to parent class. However cannot read generic types in swagger. Is it possible?

BaseController with generic types:

@ApiBearerAuth()
@Controller()
export abstract class BaseController<T, E> implements ICrudController<T, E> {

  constructor(public service: BaseService) {

  }

  // @UseGuards(AuthGuard, RolesGuard)
  @Post('get')
  @Roles(Role.USER)
  @Roles(Role.ADMIN)
  @HttpCode(200)
  async get(@Body() params: T): Promise<any> {
    let res = await this.service.getList(params);
    return {
      status: HttpConst.SuccessCode,
      data: res
    };
  }

Interface:

export interface ICrudController<QueryDto, CreateDto> {

    // getOne(id: number): Promise<EntityType>;
  
    get(query: QueryDto): Promise<any[]>;
  
    create(body: CreateDto, req: Request): Promise<any>;
  
    // update(body: UpdateDto): Promise<EntityType>;
  
    // delete(id: number): Promise<Partial<EntityType>>;
  }

Extended controller class with DTO:

export class TrainController extends BaseController<GetDtoTrain, CreateDtoTrain> {
    constructor(trainService: TrainService){
        super(trainService);
    }

DTO class:

export class CreateDtoTrain extends OmitType(TrainEntity, ['id','createdAt', 'createdUserId','updatedAt', 'updatedUserId', 'status'] as const) {}
export class UpdateDtoTrain extends OmitType(TrainEntity, ['createdAt', 'createdUserId','updatedAt', 'updatedUserId'] as const) {}

export class GetDtoTrain {
    @ApiProperty({required:false})
    where: TrainEntity;

    // @ApiProperty({required:false})
    // select: any;

    @ApiProperty()
    pagination: Pagination;
}

Swagger: enter image description here

Bilguun
  • 1
  • 1
  • In .Net this is a very standard implementation pattern, I can only speculate for typescript but having the response untyped might contribute to your swagger issues. Most swagger generators are convention based, but an untyped response to `Get` and `Create` might be leaving your controller in an abiguous state. – Chris Schaller Jul 04 '23 at 11:50
  • Another controllers with untyped response are normally in swagger. So i dont think so. – Bilguun Jul 04 '23 at 12:02

0 Answers0