Skip to content

Instantly share code, notes, and snippets.

@CarlosDanielDev
Created January 16, 2025 20:37
Show Gist options
  • Save CarlosDanielDev/547e479c61bffb24a6b1fb17695070ec to your computer and use it in GitHub Desktop.
Save CarlosDanielDev/547e479c61bffb24a6b1fb17695070ec to your computer and use it in GitHub Desktop.
// DynamicModelModule
import { Module, Global } from '@nestjs/common';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
@Global()
@Module({})
export class DynamicModelModule {
static forFeature(collectionName: string, schema: any): DynamicModule {
return {
module: DynamicModelModule,
imports: [
MongooseModule.forFeature([{ name: collectionName, schema }]),
],
providers: [
{
provide: getModelToken(collectionName),
useFactory: (connection: Connection) =>
connection.model(collectionName, schema),
inject: [Connection],
},
],
exports: [getModelToken(collectionName)],
};
}
}
// generic
import { Inject, Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { getModelToken } from '@nestjs/mongoose';
@Injectable()
export class GenericRepository {
constructor(
@Inject(getModelToken('YourDynamicModel')) private readonly model: Model<any>,
) {}
// Métodos do repositório
async createRecord(data: any) {
const record = new this.model(data);
return record.save();
}
}
// app module
import { Module } from '@nestjs/common';
import { DynamicModelModule } from './dynamic-model.module';
import { GenericRepository } from './generic-repository';
@Module({
imports: [
DynamicModelModule.forFeature('YourDynamicModel', YourDynamicSchema),
],
providers: [GenericRepository],
})
export class AppModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment