Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // tslint:disable: no-console
- import {
- Connection,
- DeepPartial,
- EntitySchema,
- getConnection,
- ObjectType
- } from 'typeorm'
- import { isArray, isPrimitive } from 'util'
- import * as models from '../../models'
- export type Model<Entity> = ObjectType<Entity> | EntitySchema<Entity> | string
- // tslint:disable-next-line: max-classes-per-file
- export class Seed<T> {
- seeds: Array<Partial<T>> = []
- insertedResults: T[] = []
- depends: string[] = []
- model: T
- constructor(model: T, seeds: Array<DeepPartial<T>>) {
- this.seeds = seeds.map(seed => {
- const newModel = Object.create(model as Object)
- return Object.assign(newModel, seed)
- })
- this.model = model
- }
- get(position: number) {
- return this.seeds[position] as T
- }
- getClassName() {
- return this.seeds[0].constructor.name
- }
- getModel() {
- return (this.model as Object).constructor
- }
- }
- // tslint:disable-next-line: max-classes-per-file
- export class Seeder {
- static seeds: Array<Seed<any>> = []
- static addSeed(seed: Seed<any>) {
- this.seeds.push(seed)
- }
- static setSeeds(seeds: Array<Seed<any>>) {
- this.seeds = seeds
- }
- static async seed() {
- await seeding(getConnection(), this.seeds)
- }
- static async cleanModel(model?: Array<Model<any>> | Model<any>) {
- const connection = getConnection()
- await connection.transaction(async trx => {
- /**
- * disable FK checks
- */
- await trx.query('SET FOREIGN_KEY_CHECKS=0;')
- if (!model) {
- for (const seed of this.seeds) {
- const modelRepo = trx.getRepository(seed.getModel())
- await modelRepo.clear()
- }
- } else if (isArray(model)) {
- for (const m of model) {
- const modelRepo = trx.getRepository(m)
- await modelRepo.clear()
- }
- } else {
- const modelRepo = trx.getRepository(model)
- await modelRepo.clear()
- }
- /**
- * enable FK checks
- */
- await trx.query('SET FOREIGN_KEY_CHECKS=1;')
- })
- }
- static async cleanModels() {
- const connection = getConnection()
- await connection.transaction(async trx => {
- /**
- * disable FK checks
- */
- await trx.query('SET FOREIGN_KEY_CHECKS=0;')
- for (const m of Object.values(models)) {
- if (m === models.CoaModel) {
- continue
- }
- const modelRepo = trx.getRepository(m)
- await modelRepo.clear()
- }
- /**
- * enable FK checks
- */
- await trx.query('SET FOREIGN_KEY_CHECKS=1;')
- })
- }
- }
- export async function seeding(connection: Connection, seeds: Array<Seed<any>>) {
- console.log('Seeding Started...')
- let unInsertedSeeds = seeds.map(seed => seed.getClassName())
- while (unInsertedSeeds.length > 0) {
- for (const seed of seeds) {
- try {
- // check depedencies
- for (const seedValue of seed.seeds) {
- for (const value of Object.values(seedValue)) {
- if (!isPrimitive(value)) {
- if (!seed.depends.find(d => d === value.constructor.name)) {
- seed.depends.push(value.constructor.name)
- }
- }
- }
- break
- }
- const seedNotInserted = unInsertedSeeds.find(
- sd => sd === seed.getClassName()
- )
- if (seedNotInserted) {
- if (seed.depends.length === 0) {
- const repo = connection.getRepository(seed.getModel())
- for (const seedValue of seed.seeds) {
- const insertedSeedValue = await repo.insert(seedValue)
- seed.insertedResults.push({
- ...seedValue,
- id: insertedSeedValue.identifiers[0].id
- })
- }
- unInsertedSeeds = unInsertedSeeds.filter(
- sd => sd !== seed.getClassName()
- )
- console.log(`Seeding successfully for model ${seed.getClassName()}`)
- } else {
- const isDepedendInserted = seed.depends.find(
- s => !unInsertedSeeds.find(us => us === s)
- )
- if (isDepedendInserted) {
- const repo = connection.getRepository(seed.getModel())
- for (const seedValue of seed.seeds) {
- const insertedSeedValue = await repo.insert(seedValue)
- seed.insertedResults.push({
- ...seedValue,
- id: insertedSeedValue.identifiers[0].id
- })
- }
- unInsertedSeeds = unInsertedSeeds.filter(
- sd => sd !== seed.getClassName()
- )
- console.log(
- `Seeding successfully for model ${seed.getClassName()}`
- )
- }
- }
- }
- } catch (error) {
- console.log(
- `Error when seeding model ${seed.getClassName()} : ${error.message}`
- )
- throw error
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement