Skip to content

Commit

Permalink
add module for db-seeding with factories, PersonFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
DPDS93CT committed Nov 15, 2023
1 parent 3abacf6 commit 7c064ae
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 3 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"start:console": "nest start console --",
"db:init": "npm run start:console -- db init",
"db:seed": "npm run start:console -- db seed",
"db:seedwf": "npm run start:console -- db seedwf",
"setup": "npm run db:init"
},
"dependencies": {
Expand All @@ -39,7 +40,7 @@
"@mikro-orm/core": "^5.7.11",
"@mikro-orm/nestjs": "^5.1.8",
"@mikro-orm/postgresql": "^5.7.11",
"@mikro-orm/seeder": "^5.9.3",
"@mikro-orm/seeder": "^5.8.6",
"@nestjs/axios": "^3.0.1",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^3.1.1",
Expand Down
4 changes: 3 additions & 1 deletion src/console/console.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { LoggingModule } from '../shared/logging/index.js';
import { DbConsole } from './db.console.js';
import { DbInitConsole } from './db-init.console.js';
import { DbSeedConsole } from './db-seed.console.js';
import { DbSeedWFConsole } from './db-seed-with-factory.js';

@Module({
imports: [
Expand All @@ -29,6 +30,7 @@ import { DbSeedConsole } from './db-seed.console.js';
MikroOrmModule.forRootAsync({
useFactory: (config: ConfigService<ServerConfig, true>) => {
return defineConfig({
debug: true,
clientUrl: config.getOrThrow<DbConfig>('DB').CLIENT_URL,
dbName: config.getOrThrow<DbConfig>('DB').DB_NAME,
entities: ['./dist/**/*.entity.js'],
Expand All @@ -43,6 +45,6 @@ import { DbSeedConsole } from './db-seed.console.js';
inject: [ConfigService],
}),
],
providers: [DbConsole, DbInitConsole, DbSeedConsole],
providers: [DbConsole, DbInitConsole, DbSeedConsole, DbSeedWFConsole],
})
export class ConsoleModule {}
26 changes: 26 additions & 0 deletions src/console/db-seed-with-factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { CommandRunner, SubCommand } from 'nest-commander';
import { LoggerService } from '../shared/logging/index.js';
import { MikroORM } from '@mikro-orm/core';
import { PersonFactory } from '../../test/person-factory.js';
import { PersonEntity } from '../modules/person/persistence/person.entity.js';

@SubCommand({ name: 'seedwf', description: 'creates seed data in the database' })
export class DbSeedWFConsole extends CommandRunner {
public constructor(
private readonly orm: MikroORM,
private readonly logger: LoggerService,
) {
super();
}

public override async run(_passedParams: string[], _options?: Record<string, unknown>): Promise<void> {
this.logger.info('Create seed data in the database with factories ...');
/* eslint-disable @typescript-eslint/typedef */
const forkedEm = this.orm.em.fork();
const persons: PersonEntity[] = new PersonFactory(forkedEm).make(1);
for (const person of persons) {
await forkedEm.persistAndFlush(person);
}
this.logger.info('Created seed data successfully');
}
}
3 changes: 2 additions & 1 deletion src/console/db.console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { Command, CommandRunner } from 'nest-commander';
import { DbInitConsole } from './db-init.console.js';
import { LoggerService } from '../shared/logging/index.js';
import { DbSeedConsole } from './db-seed.console.js';
import { DbSeedWFConsole } from './db-seed-with-factory.js';

@Command({
name: 'db',
arguments: '<sub-command>',
description: 'runs commands to manage the database',
subCommands: [DbInitConsole, DbSeedConsole],
subCommands: [DbInitConsole, DbSeedConsole, DbSeedWFConsole],
})
export class DbConsole extends CommandRunner {
public constructor(private readonly logger: LoggerService) {
Expand Down
50 changes: 50 additions & 0 deletions test/person-factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { PersonEntity } from '../src/modules/person/persistence/person.entity.js';
import { Factory, Faker } from '@mikro-orm/seeder';
import { EntityData } from '@mikro-orm/core';
import { faker as facer, SexType } from '@faker-js/faker';
import { Geschlecht, Vertrauensstufe } from '../src/modules/person/domain/person.enums.js';

export class PersonFactory extends Factory<PersonEntity> {
/* eslint-disable @typescript-eslint/typedef */
public model = PersonEntity;

protected definition(faker: Faker): EntityData<PersonEntity> {
const sexType: SexType = this.getRandomSex();
return {
keycloakUserId: facer.string.uuid(),
referrer: facer.string.numeric(),
mandant: facer.string.numeric(),
stammorganisation: facer.string.numeric(),
familienname: facer.person.lastName(),
vorname: facer.person.firstName(sexType),
nameTitel: facer.string.alpha(),
nameAnrede: [facer.person.prefix(sexType)],
namePraefix: [facer.person.prefix(sexType)],
nameSuffix: [],
nameSortierindex: facer.string.alpha(),
geburtsdatum: faker.date.past(),
geburtsort: facer.location.city(),
geschlecht: this.getRandomSex() === 'female' ? Geschlecht.W : Geschlecht.M,
vertrauensstufe: this.getRandomVetrauensstufe(),
auskunftssperre: Math.random() < 0.5,
};
}

private getRandomSex(): SexType {
return Math.random() < 0.5 ? 'female' : 'male';
}

private getRandomVetrauensstufe(): Vertrauensstufe {
const randomInt: number = Math.floor(Math.random() * 4) + 1;
switch (randomInt) {
case 1:
return Vertrauensstufe.KEIN;
case 2:
return Vertrauensstufe.UNBE;
case 3:
return Vertrauensstufe.TEIL;
default:
return Vertrauensstufe.VOLL;
}
}
}

0 comments on commit 7c064ae

Please sign in to comment.