I have created the following function for creating a dynamic controller:
import type { Type } from '@nestjs/common';
import { Body, Controller, Post } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import type { ObjectLiteral, DeepPartial } from 'typeorm';
import { Repository } from 'typeorm';
type Constructor<I> = new (...args: unknown[]) => I; // Main Point
export function dynamicController<T extends ObjectLiteral, D extends DeepPartial<T>>(
entity: Constructor<T>,
): Type {
@Controller(entity.name.toLowerCase())
class DynamicController {
constructor(
@InjectRepository(entity)
private readonly repository: Repository<T>,
) {}
@Post()
async createEntity(@Body() dtoBody: D): Promise<T> {
const newEntity = this.repository.create({ ...dtoBody });
const savedEntity = await this.repository.save(newEntity);
return savedEntity;
}
}
return DynamicController;
}
However, if for instance I create a controller using dynamicController<Patient, PatientDto>(Patient) what happens is it does sucessfully register a POST endpoint but dtoBody parameter isn't actually being validated against PatientDto..
Is there any way to solve this?