nestjs-seeder
nestjs-seeder copied to clipboard
How to use with typeORM
Use with typeOrm
i want to use seeding with typeOrm but stay db error how can i solve this
Here's a small TypeORM example for future reference:
user.entity.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
Index,
} from 'typeorm';
import { Factory } from 'nestjs-seeder';
@Entity('user')
export class User {
@PrimaryGeneratedColumn('uuid')
id!: string;
@Factory((faker) => {
return faker!.string.alphanumeric(28);
})
@Index({ unique: true })
@Column({ nullable: false })
userId!: string;
@Factory((faker) => faker.person.fullName())
name!: string;
}
user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
DeepPartial,
InsertResult,
Repository,
Not,
IsNull
} from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
save(users: DeepPartial<User>[]) {
return this.userRepository.save(users);
}
delete(criteria: Parameters<Repository<User>['delete']>[0]) {
return this.userRepository.delete({
id: Not(IsNull())
});
}
}
user.seeder.ts
import { Injectable } from '@nestjs/common';
import { Seeder, DataFactory } from 'nestjs-seeder';
import { User } from '../users/user.entity';
import { DeepPartial, In } from 'typeorm';
import { UserService } from './user.service';
@Injectable()
export class UsersSeeder implements Seeder {
users: DeepPartial<User>[];
constructor(private readonly userService: UserService) {
// Generate 10 users.
this.users = DataFactory.createForClass(User).generate(
10,
) as DeepPartial<User>[];
}
async seed() {
return this.userService.save(this.users);
}
async drop() {
return this.userService.deleteAll()
}
}
user.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { UserService } from './user.service';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
user.seeder.ts
import { seeder } from 'nestjs-seeder';
import { UsersSeeder } from './user.seeder';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmConfigService } from '../typeorm-config/typeorm-config.service';
import { UserModule } from '../user.module';
seeder({
imports: [
TypeOrmModule.forFeature([User])
UserModule,
],
}).run([UsersSeeder]);
Install ts-node
and add to package.json:
"seed": "ts-node -r tsconfig-paths/register ./src/user.seeder.ts"
"seed:refresh": "ts-node -r tsconfig-paths/register ./src/user.seeder.ts --refresh"
and run
npm run seed
or
npm run seed:refresh
@edwardanthony Would you want a PR to README for this?
@petetnt I am having troubles setting it up. Where do you set TypeORM configuration? And is there a reason you import the User feature in both the user.seeder.ts
and the UserModule
?
If I add TypeOrmModule.forRoot
(like I already do in AppModule) I am getting error:
[Nest] 3389 - 06.08.2024 12.26.08 ERROR [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.
Potential solutions:
- Is TypeOrmCoreModule a valid NestJS module?
- If ModuleRef is a provider, is it part of the current TypeOrmCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
@Module({
imports: [ /* the Module containing ModuleRef */ ]
})
Error: Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.
Potential solutions:
- Is TypeOrmCoreModule a valid NestJS module?
- If ModuleRef is a provider, is it part of the current TypeOrmCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
@Module({
imports: [ /* the Module containing ModuleRef */ ]
})
Sorry @simplenotezy , I kinda yolo'd the example there and I don't have access to the branch at the moment. I think I duplicate import might be just a copypasta error, I think the import in module should be
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useClass: TypeOrmConfigService,
}),
or similar forRoot
import as per docs https://docs.nestjs.com/techniques/database