Skip to content

About

🌱 A delightful way to seed test data into your database.

Resources

Stars

80 stars

Watchers

2 watching

Forks

Β 
Β 

Latest commit

Β 

History

727 Commits

Folders and files

Repository files navigation

logo

TypeORM Seeding

License Semantic release Biome Coveralls main branch

A delightful way to seed test data into your database.
Inspired by the awesome framework laravel in PHP, MikroORM seeding and the repositories from pleerock

Made with ❀️ by Gery Hirschfeld, Jorge Bodega and contributors


Contents

Installation

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

After that, install the extension. Add development flag if you are not using seeders nor factories in production code.

npm i [-D] @jorgebodega/typeorm-seeding
yarn add [-D] @jorgebodega/typeorm-seeding
pnpm add [-D] @jorgebodega/typeorm-seeding

Compatibility

Version TypeORM Node.js Branch Status
8.x ^0.3.28 ^20.19.0 || ^22.12.0 || >=24.11.0 8.x Security fixes only, published with the compatibility npm tag.
9.x >=1.0.0 ^20.19.0 || ^22.13.0 || >=24.11.0 main Stable.

Node.js ranges follow the ones supported by TypeORM.

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 entity factory and/or seed script.

Entity

@Entity()
class User {
  @PrimaryGeneratedColumn('increment')
  id!: number

  @Column()
  name!: string

  @Column()
  lastName!: string

  @Column()
  email!: string

  @OneToMany(() => Pet, (pet) => pet.owner)
  pets?: Pet[]

  @ManyToOne(() => Country, (country) => country.users, { nullable: false })
  @JoinColumn()
  country!: Country
}

Seeder

class UserSeeder extends Seeder {
  async run(dataSource: DataSource) {
    const users: User[] = [...]
    await dataSource.createEntityManager().save<User>(users)
  }
}

Seeder

Seeder class is how we provide a way to insert data into databases, and could be executed by the command line or by helper method. Is an abstract class with one method to be implemented, and a helper function to run some more seeder sequentially.

class UserSeeder extends Seeder {
  async run(dataSource: DataSource) {
    ...
  }
}

The seeder class must be exported from its file (default or named export) to be found by the CLI.

export default class UserSeeder extends Seeder {
  async run(dataSource: DataSource) {
    ...
  }
}

run

This function is the one that needs to be defined when extending the class.

run(dataSource: DataSource): Promise<void>
async run(dataSource: DataSource) {
    const users: User[] = [...]
    await dataSource.createEntityManager().save<User>(users)
}

CLI Configuration

There is a command that allows you to execute multiple seeders from cli.

typeorm-seeding seed -d path/to/datasource src/seeders/*.ts

Add the following script to your package.json file to configure them.

"scripts": {
  "seed:run": "typeorm-seeding seed -d path/to/datasource",
  ...
}

seed

This command executes the seeders found in the given paths. Glob patterns are supported.

typeorm-seeding seed -d <dataSourcePath> <paths...>

Every exported class extending Seeder in the matched files is executed once. Abstract classes that do not implement run are skipped.

flowchart TD
    A["typeorm-seeding seed -d dataSourcePath paths..."] --> B["Load the data source file"]
    B -- fails --> E1["DataSourceImportationError"]
    B --> C["Import every exported Seeder subclass from the paths"]
    C -- fails or none found --> E2["SeederImportationError"]
    C --> D["Initialize the data source"]
    D -- fails --> E3["SeederExecutionError"]
    D --> F["Run the seeders one by one"]
    F -- a seeder fails --> E3
    F --> G["Destroy the data source"]
Loading

Each error keeps the original failure in its cause, and the command exits with a non-zero code.

Options
Option Default Description
--dataSource or -d ./datasource.ts Path of the data source

Testing features

We provide some testing features that we already use to test this package, like connection configuration. Use useDataSource to register a data source and useSeeders to run seeders from your tests.

useSeeders

Execute one or more seeders.

useSeeders(entrySeeders: Constructable<Seeder> | Constructable<Seeder>[]): Promise<void>

useDataSource

Register the data source used by useSeeders. If the data source is not initialized when provided, can be initialized with the forceInitialization flag.

useDataSource(dataSource: DataSource): Promise<void>
useDataSource(dataSource: DataSource, overrideOptions: Partial<DataSourceOptions>): Promise<void>
useDataSource(dataSource: DataSource, forceInitialization: boolean): Promise<void>
useDataSource(
  dataSource: DataSource,
  overrideOptions: Partial<DataSourceOptions>,
  forceInitialization: boolean,
): Promise<void>

Factory

Factory related code has been removed from this package, now on @jorgebodega/typeorm-factory.

Development

Use the Node.js version in .node-version and pnpm (corepack enable).

pnpm install
pnpm checks     # format, lint (including import order) and typecheck
pnpm lint:fix   # apply safe lint fixes and sort imports
pnpm test       # jest against in-memory sqlite
pnpm build
  • next: development branch. Releases prereleases with the next npm tag.
  • main: stable releases with the latest npm tag.
  • N.x: maintenance branch of a previous major. Security fixes only, released with the compatibility npm tag.

Commits follow Conventional Commits. Releases are created by the manual Release workflow (semantic-release); run it with dry-run first.

About

🌱 A delightful way to seed test data into your database.

Resources

Stars

80 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages