Skip to content

w3tecch/typeorm-seeding

Folders and files

NameName
Last commit message
Last commit date

Latest commit

d82c7ad Β· Apr 11, 2020
Apr 11, 2020
Apr 11, 2020
Sep 25, 2018
Apr 11, 2020
Apr 9, 2020
Apr 9, 2020
Oct 19, 2019
Oct 19, 2019
Apr 10, 2020
Sep 26, 2018
Apr 11, 2020
Apr 10, 2020
Apr 11, 2020
Apr 9, 2020
Apr 11, 2020
Sep 25, 2018
Sep 25, 2018
Apr 11, 2020

Repository files navigation

w3tec

TypeORM Seeding

Sematic-Release Dependency Build Status

A delightful way to seed test data into your database.
Inspired by the awesome framework laravel in PHP and of the repositories from pleerock
Made with ❀️ by w3tech, Gery Hirschfeld and contributors


divider

❯ Introduction

Isn't it exhausting to create some sample data for your database, well this time is over!

How does it work? Just create a factory for your entities (models) and a seed script.

divider

❯ Installation

Before using this TypeORM extension please read the TypeORM Getting Started documentation. This explains how to setup a TypeORM project.

You can install our extension with npm or yarn.

npm i typeorm-seeding

or with yarn

yarn add typeorm-seeding

Optional, for Faker types

npm install -D @types/faker

Configuration

To configure the path to your seeds and factories change the TypeORM config file(ormconfig.js or ormconfig.json).

module.exports = {
  ...
  seeds: ['src/seeds/**/*{.ts,.js}'],
  factories: ['src/factories/**/*{.ts,.js}'],
}

or add the following variables to your .env file.

TYPEORM_SEEDING_FACTORIES=src/factories/**/*{.ts,.js}
TYPEORM_SEEDING_SEEDS=src/seeds/**/*{.ts,.js}

divider

❯ Writing Seeders

The seeds files define how much and how the data are connected with each other. The files will be executed alphabetically.

import { Factory, Seeder } from 'typeorm-seeding'
import { Connection } from 'typeorm'
import { User } from '../entities'

export default class CreateUsers implements Seeder {
  public async run(factory: Factory, connection: Connection): Promise<any> {
    await connection
      .createQueryBuilder()
      .insert()
      .into(User)
      .values([
        { firstName: 'Timber', lastName: 'Saw' },
        { firstName: 'Phantom', lastName: 'Lancer' },
      ])
      .execute()
  }
}

❯ Running Seeders

Once you have written your seeder, you can add this script to your package.json.

  "scripts": {
    "seed": "ts-node ./node_modules/typeorm-seeding/dist/cli.js seed"
    ...
  }

And then

npm run seed

Using Model Factories

For all entities we want to seed, we need to define a factory. To do so we give you the awesome faker library as a parameter into your factory. Then create your "fake" entity and return it. Those factory files should be in the src/database/factories folder and suffixed with .factory like src/database/factories/User.factory.ts.

Settings can be used to pass some static value into the factory.

import Faker from 'faker'
import { define } from 'typeorm-seeding'
import { User } from '../entities'

define(User, (faker: typeof Faker, settings: { roles: string[] }) => {
  const gender = faker.random.number(1)
  const firstName = faker.name.firstName(gender)
  const lastName = faker.name.lastName(gender)
  const email = faker.internet.email(firstName, lastName)

  const user = new User()
  user.firstName = firstName
  user.lastName = lastName
  user.email = email
  user.roles = settings.roles
  return user
})

Handle relation in the entity factory like this.

import Faker from 'faker'
import { define } from 'typeorm-seeding'
import { Pet } from '../entities'

define(Pet, (faker: typeof Faker, settings: undefined) => {
  const gender = faker.random.number(1)
  const name = faker.name.firstName(gender)

  const pet = new Pet()
  pet.name = name
  pet.age = faker.random.number()
  pet.user = factory(User)({ roles: ['admin'] }) as any
  return pet
})

In your seed script you can use the factory like this. With the second function, accepting your settings defined in the factories, you are able to create different variations of entities.

import { Factory, Seeder } from 'typeorm-seeding'
import { Connection } from 'typeorm'
import { User } from '../entities'

export default class CreateUsers implements Seeder {
  public async run(factory: Factory, connection: Connection): Promise<any> {
    await factory(User)({ roles: [] }).seedMany(10)
  }
}

Here an example with nested factories. You can use the .map() function to alter the generated value before they get persisted.

...
await factory(User)()
    .map(async (user: User) => {
        const pets: Pet[] = await factory(Pet)().seedMany(2);
        const petIds = pets.map((pet: Pet) => pet.Id);
        await user.pets().attach(petIds);
    })
    .seedMany(5);
...

To override specific properties in all the generated entities, you can send an additional object containing the properties that you want to override as the first argument in the .make() and .seed() methods, or as second argument in the .makeMany() and .seedMany() methods.

...
await factory(User)()
    .seedMany(10, { roles: ['admin'], firstName: 'John' });
...

To deal with relations you can use the entity manager like this.

export default class CreatePets implements Seeder {
  public async run(factory: Factory, connection: Connection): Promise<any> {
    const em = connection.createEntityManager()

    await times(10, async (n) => {
      // This creates a pet in the database
      const pet = await factory(Pet)().seed()
      // This only returns a entity with fake data
      const user = await factory(User)({ roles: ['admin'] }).make()
      user.pets = [pet]
      await em.save(user)
    })
  }
}

Now you are able to execute your seeds with this command npm run seed.

Note: Be sure to specify which config file you are using (ormconfig.json or ormconfig.js) with the --config cli option.

CLI Options

Option Default Description
--seed or -s null Option to specify a specific seeder class to run individually.
--connection or -c null Name of the typeorm connection. Required if there are multiple connections.
--configName or -n ormconfig.js Name to the typeorm config file.
--root or -r process.cwd() Path to the typeorm config file.

❯ License

MIT