I want to create dynamic service by user from frontend;
For example, I create a form with moduleName, moduleUrl, schema options,
and then save with createModule service to let nestjs to dynamic create controller with prefix of moduleUrl, create mongodb schema with schema options, finally the nestjs will have module and the database will have new collection. Here is my code
DynamicControllerService
@Controller()
export class DynamicControllerService {
constructor(
private dynamicSchemaService: DynamicSchemaService,
private dynamicService: DynamicService
) {}
createController(path: string, schemaData: any): any {
const schema = this.dynamicSchemaService.createSchema(schemaData)
const services = this.dynamicService.createServices(schema)
@Controller(path)
class DynamicController extends CrudController<typeof schema>{
constructor(protected readonly service: typeof services) {
super(service);
}
}
return DynamicController;
}
}
DynamicSchemaService
@Injectable()
export class DynamicSchemaService {
createSchema(data: any): any {
@Schema()
class DynamicSchema extends Document {
constructor(schemaData: any) {
super();
Object.keys(schemaData).forEach(key => {
this[key] = schemaData[key];
});
}
}
Object.keys(data).forEach(key => {
Prop()(DynamicSchema.prototype, key);
});
return SchemaFactory.createForClass(DynamicSchema);
}
}