5
I am currently studying Typeorm, and wanted to create a generic controller, as it will always be the same CRUD operations. I know I can solve with native Typeorm solutions, such as getRepository()
, I have even resolved it, but now I want to remove this doubt that persists...
So, in the way I tried earlier, my entities are extending the class BaseEntity
, to be able to access the method getRepository()
directly in the class. So:
export abstract class AbstractEntity extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({default: true})
ativo: boolean;
@CreateDateColumn()
createdAt: string;
@UpdateDateColumn({ type: "timestamp" })
updatedAt: number;
}
And this class just to illustrate:
export class Pessoa extends AbstractEntity {
@Column()
nome: string;
}
I was hoping to create a generic controller more or less like this:
class GenericController<T extends BaseEntity> {
async getAll(request: Request, response: Response, nextFunction: NextFunction) {
return await T.getRepository().find();
}
}
To use thus:
export default class PessoaRoute {
pessoaController = new GenericController<Pessoa>()
constructor() {
this.initializeRoutes();
}
initializeRoutes() {
this.router.get('/', this.pessoaController.getAll);
}
}
The problem I have is that in GenericController
I don’t have access to the methods I need through T
, not even it is recognized as existing in Typescript, that in that mode I intend to use: T.getRepository()
.
I read a little in the Typescript documentation but I didn’t understand why it didn’t work.