Skip to content

Instantly share code, notes, and snippets.

@TechnotronicOz
Created July 28, 2021 16:49
Show Gist options
  • Save TechnotronicOz/95c89b3ad2072d0556bce10a55112fee to your computer and use it in GitHub Desktop.
Save TechnotronicOz/95c89b3ad2072d0556bce10a55112fee to your computer and use it in GitHub Desktop.
barf
import { EntityManager, MikroORM } from '@mikro-orm/core';
import { Logger } from '@nestjs/common';
import config from '../mikro-orm.config';
import { fixtureGenerationSteps } from './generation-steps';
import { asyncForEach, partitionArray } from './util/array';
import { Timer } from './util/timer';
const logger = new Logger('fixture.main');
const entityInserter = (em: EntityManager) => async (
arr: any[],
name: string
) => {
const partedArr = partitionArray(arr, 2000);
const inserterTimer = new Timer();
inserterTimer.start();
await asyncForEach(partedArr, async (part: any[], i: number) => {
logger.log(
`asyncForEach [name=${name}, part ${i + 1} of ${
partedArr.length
}, dur=${inserterTimer.getTime()}]`
);
await em.persist(part).flush();
// once it is flushed, we don't need to keep our reference
// around in the array so we set it to an empty array
partedArr[i] = [];
});
inserterTimer.stop();
logger.log(`complete entity insertion [durr=${inserterTimer.getTime()}]`);
};
async function bootstrap() {
const orm = await MikroORM.init(config);
logger.log('connected, beginning fixture insertion...');
// do this in a transaction so we don't have partial inserts in case of failure
// eslint-disable-next-line max-statements
await orm.em.transactional(async (em) => {
const inserter = entityInserter(em);
const ot = new Timer();
ot.start();
await asyncForEach(fixtureGenerationSteps, async (step, i) => {
const t = new Timer();
logger.log(
`saving ${step.name}... [${i + 1} of ${fixtureGenerationSteps.length}]`
);
t.start();
await inserter(step.entities, step.name);
t.stop();
logger.log(`done saving ${step.name}, durr=${t.getTime()}`);
});
ot.stop();
logger.log(`done [durr=${ot.getTime()}]`);
});
}
bootstrap()
.then(() => {
logger.log('done inserting all fixtures! 🤙');
process.exit(0);
})
.catch((err) => {
logger.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment