Nest js with swagger decorators, re decorate methods

Viewed 1320

I'm building an API with nest js with swagger, I builded an abstract class "BaseController" with the CRUD methods, the idea is extends from the BaseController to the controllers passing the entity. My question is how I could re-decorate the inherited methods to implement the swagger decorators in the different controllers (with different entities)?

This is my BaseController:

import {
  Body,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  InternalServerErrorException,
  Param,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { UpdateResult } from 'typeorm';
import { BaseService } from './base.service';
import { ApiException } from '@models/api-exception.model';

export abstract class BaseController<T> {
  protected readonly service: BaseService<T>;

  constructor(service: BaseService<T>) {
    this.service = service;
  }

  @Get()
  root(@Query('filter') filter = {}): Promise<T[]> {
    try {
      return this.service.find(filter);
    } catch(e) {
      throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Get(':id')
  getById(@Param('id') id: string | number): Promise<T> {
    try {
      return this.service.findById(id);
    } catch(e) {
      throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Post()
  create(@Body() body: T): Promise<T> {
    try {
      return this.service.create(body);
    } catch(e) {
      throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Put()
  update(@Body() body: { id: string | number } & T): Promise<UpdateResult> {
    return this.service.update(body.id, body);
  }

  @Delete(':id')
  delete(@Param('id') id: string | number) {
    try {
      return this.service.delete(id);
    } catch(e) {
      throw new InternalServerErrorException(e);
    }
  }
}

For example if a create "TodoController extends BaseController" how I could apply the swagger decorators? Is there a way to make something like "dynamic decorators"?

0 Answers
Related