conceptadev / typeorm-seeding

A simple but powerful database seeder for TypeORM ^0.3.0
https://www.npmjs.com/package/@concepta/typeorm-seeding
MIT License
12 stars 8 forks source link

Create if not exists? #7

Closed agmcleod closed 5 months ago

agmcleod commented 5 months ago

Hey there, I appreciate you folks working on a version that works with 0.3 typeorm. Im working on updating the dependencies of a project, where we had written seed files like so:

import data from './stations.json'

export default class StationSeed implements Seeder {
  async run(factory: Factory, connection: Connection) {
    await connection
      .createQueryBuilder()
      .insert()
      .into(Station)
      .values(
        data
      )
      .orIgnore('Data Already Exists')
      .execute()
  }
}

This would allow us to ignore anything violating unique constraints that we have on external identifiers and such. It doesn't seem with the factory I can query existing data. Is there a way for me to have the seed complete and only insert new data?

MrMaz commented 5 months ago

@agmcleod this is a great question, let me see if i can help you.

Both Seeder and Factory have an undocumented repository() method that you can pass any Entity class and get the repository for it... see:

https://github.com/conceptadev/typeorm-seeding/blob/main/src/seeder.ts#L61 https://github.com/conceptadev/typeorm-seeding/blob/main/src/factory.ts#L194

So inside your Seeder run() implementation, you can call the Factory.make() which will create the object but not persist it. Then use the repository to query if these objects already exist. If not, you can call the Factory.save() on the objects you want to persist.

agmcleod commented 5 months ago

@MrMaz ty, ill give that a try, and ill follow up to let you know how it goes.

agmcleod commented 5 months ago

This worked thank you. I was able to use this.repository(Entity) and from there use my original code calling to create a query builder.