SHARE
TWEET

Seeder For Typeorm

a guest Nov 12th, 2019 156 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // tslint:disable: no-console
  2.  
  3. import {
  4.   Connection,
  5.   DeepPartial,
  6.   EntitySchema,
  7.   getConnection,
  8.   ObjectType
  9. } from 'typeorm'
  10. import { isArray, isPrimitive } from 'util'
  11. import * as models from '../../models'
  12. export type Model<Entity> = ObjectType<Entity> | EntitySchema<Entity> | string
  13.  
  14. // tslint:disable-next-line: max-classes-per-file
  15. export class Seed<T> {
  16.   seeds: Array<Partial<T>> = []
  17.   insertedResults: T[] = []
  18.   depends: string[] = []
  19.   model: T
  20.   constructor(model: T, seeds: Array<DeepPartial<T>>) {
  21.     this.seeds = seeds.map(seed => {
  22.       const newModel = Object.create(model as Object)
  23.       return Object.assign(newModel, seed)
  24.     })
  25.     this.model = model
  26.   }
  27.  
  28.   get(position: number) {
  29.     return this.seeds[position] as T
  30.   }
  31.   getClassName() {
  32.     return this.seeds[0].constructor.name
  33.   }
  34.   getModel() {
  35.     return (this.model as Object).constructor
  36.   }
  37. }
  38.  
  39. // tslint:disable-next-line: max-classes-per-file
  40. export class Seeder {
  41.   static seeds: Array<Seed<any>> = []
  42.   static addSeed(seed: Seed<any>) {
  43.     this.seeds.push(seed)
  44.   }
  45.  
  46.   static setSeeds(seeds: Array<Seed<any>>) {
  47.     this.seeds = seeds
  48.   }
  49.  
  50.   static async seed() {
  51.     await seeding(getConnection(), this.seeds)
  52.   }
  53.  
  54.   static async cleanModel(model?: Array<Model<any>> | Model<any>) {
  55.     const connection = getConnection()
  56.     await connection.transaction(async trx => {
  57.       /**
  58.        * disable FK checks
  59.        */
  60.       await trx.query('SET FOREIGN_KEY_CHECKS=0;')
  61.       if (!model) {
  62.         for (const seed of this.seeds) {
  63.           const modelRepo = trx.getRepository(seed.getModel())
  64.           await modelRepo.clear()
  65.         }
  66.       } else if (isArray(model)) {
  67.         for (const m of model) {
  68.           const modelRepo = trx.getRepository(m)
  69.           await modelRepo.clear()
  70.         }
  71.       } else {
  72.         const modelRepo = trx.getRepository(model)
  73.         await modelRepo.clear()
  74.       }
  75.       /**
  76.        * enable FK checks
  77.        */
  78.       await trx.query('SET FOREIGN_KEY_CHECKS=1;')
  79.     })
  80.   }
  81.  
  82.   static async cleanModels() {
  83.     const connection = getConnection()
  84.     await connection.transaction(async trx => {
  85.       /**
  86.        * disable FK checks
  87.        */
  88.       await trx.query('SET FOREIGN_KEY_CHECKS=0;')
  89.  
  90.       for (const m of Object.values(models)) {
  91.         if (m === models.CoaModel) {
  92.           continue
  93.         }
  94.         const modelRepo = trx.getRepository(m)
  95.         await modelRepo.clear()
  96.       }
  97.       /**
  98.        * enable FK checks
  99.        */
  100.       await trx.query('SET FOREIGN_KEY_CHECKS=1;')
  101.     })
  102.   }
  103. }
  104.  
  105. export async function seeding(connection: Connection, seeds: Array<Seed<any>>) {
  106.   console.log('Seeding Started...')
  107.   let unInsertedSeeds = seeds.map(seed => seed.getClassName())
  108.   while (unInsertedSeeds.length > 0) {
  109.     for (const seed of seeds) {
  110.       try {
  111.         // check depedencies
  112.         for (const seedValue of seed.seeds) {
  113.           for (const value of Object.values(seedValue)) {
  114.             if (!isPrimitive(value)) {
  115.               if (!seed.depends.find(d => d === value.constructor.name)) {
  116.                 seed.depends.push(value.constructor.name)
  117.               }
  118.             }
  119.           }
  120.           break
  121.         }
  122.  
  123.         const seedNotInserted = unInsertedSeeds.find(
  124.           sd => sd === seed.getClassName()
  125.         )
  126.         if (seedNotInserted) {
  127.           if (seed.depends.length === 0) {
  128.             const repo = connection.getRepository(seed.getModel())
  129.             for (const seedValue of seed.seeds) {
  130.               const insertedSeedValue = await repo.insert(seedValue)
  131.               seed.insertedResults.push({
  132.                 ...seedValue,
  133.                 id: insertedSeedValue.identifiers[0].id
  134.               })
  135.             }
  136.             unInsertedSeeds = unInsertedSeeds.filter(
  137.               sd => sd !== seed.getClassName()
  138.             )
  139.             console.log(`Seeding successfully for model ${seed.getClassName()}`)
  140.           } else {
  141.             const isDepedendInserted = seed.depends.find(
  142.               s => !unInsertedSeeds.find(us => us === s)
  143.             )
  144.             if (isDepedendInserted) {
  145.               const repo = connection.getRepository(seed.getModel())
  146.               for (const seedValue of seed.seeds) {
  147.                 const insertedSeedValue = await repo.insert(seedValue)
  148.                 seed.insertedResults.push({
  149.                   ...seedValue,
  150.                   id: insertedSeedValue.identifiers[0].id
  151.                 })
  152.               }
  153.               unInsertedSeeds = unInsertedSeeds.filter(
  154.                 sd => sd !== seed.getClassName()
  155.               )
  156.               console.log(
  157.                 `Seeding successfully for model ${seed.getClassName()}`
  158.               )
  159.             }
  160.           }
  161.         }
  162.       } catch (error) {
  163.         console.log(
  164.           `Error when seeding model ${seed.getClassName()} : ${error.message}`
  165.         )
  166.         throw error
  167.       }
  168.     }
  169.   }
  170. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top