Reputation: 81
In a NestJS with TypeORM I tried to seed a MariaDB database using typeorm-extension package. The problem is that sometimes while running the script to seed the database it creates duplicated entries which throws an exception and stopping the database seeding.
country.factory.ts
import { Country } from 'src/locations/countries/entities/country.entity';
import { setSeederFactory } from 'typeorm-extension';
export default setSeederFactory(Country, (faker) => {
const country = new Country({
name: faker.location.country(),
status: faker.datatype.boolean(),
});
return country;
});
country.seeder.ts
import { Country } from 'src/locations/countries/entities/country.entity';
import { DataSource } from 'typeorm';
import { Seeder, SeederFactoryManager } from 'typeorm-extension';
import { quantities } from '../quantities';
export default class CountrySeeder implements Seeder {
public async run(
dataSource: DataSource,
factoryManager: SeederFactoryManager,
): Promise<void> {
await dataSource.query('SET FOREIGN_KEY_CHECKS=0;');
await dataSource.query('ALTER TABLE countries AUTO_INCREMENT=1;');
const countryFactory = factoryManager.get(Country);
await countryFactory.saveMany(quantities.countries);
await dataSource.query('SET FOREIGN_KEY_CHECKS=1;');
}
}
I used an array to store the already created entries to compare the new ones but did not work or i was using it the wrong way
Upvotes: 0
Views: 79