{"id":13433208,"url":"https://github.com/w3tecch/typeorm-seeding","last_synced_at":"2025-05-15T00:06:57.335Z","repository":{"id":33991873,"uuid":"150270033","full_name":"w3tecch/typeorm-seeding","owner":"w3tecch","description":"🌱 A delightful way to seed test data into your database.","archived":false,"fork":false,"pushed_at":"2023-12-29T20:27:33.000Z","size":1248,"stargazers_count":903,"open_issues_count":40,"forks_count":132,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-05-08T22:36:33.651Z","etag":null,"topics":["cli","data-seeding","database","seed","seeding","typeorm","typeorm-extension","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/typeorm-seeding","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/w3tecch.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-09-25T13:30:22.000Z","updated_at":"2025-05-05T16:54:56.000Z","dependencies_parsed_at":"2024-05-04T19:44:08.102Z","dependency_job_id":"65cff7da-4582-4c66-8314-086ddb8ca9fd","html_url":"https://github.com/w3tecch/typeorm-seeding","commit_stats":{"total_commits":122,"total_committers":21,"mean_commits":5.809523809523809,"dds":0.3278688524590164,"last_synced_commit":"4565f66bfb0223dae44cfd1cfa56dc3ae1e5341f"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w3tecch%2Ftypeorm-seeding","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w3tecch%2Ftypeorm-seeding/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w3tecch%2Ftypeorm-seeding/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w3tecch%2Ftypeorm-seeding/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/w3tecch","download_url":"https://codeload.github.com/w3tecch/typeorm-seeding/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253377260,"owners_count":21898938,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","data-seeding","database","seed","seeding","typeorm","typeorm-extension","typescript"],"created_at":"2024-07-31T02:01:22.489Z","updated_at":"2025-05-15T00:06:57.272Z","avatar_url":"https://github.com/w3tecch.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"./logo.png\" alt=\"logo\" width=\"160\" /\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\" style=\"text-align: center;\"\u003eTypeORM Seeding\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/typeorm-seeding\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/typeorm-seeding\" alt=\"NPM package\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://travis-ci.org/w3tecch/typeorm-seeding\"\u003e\n    \u003cimg src=\"https://travis-ci.org/w3tecch/typeorm-seeding.svg?branch=master\" alt=\"Build Status\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://david-dm.org/w3tecch/typeorm-seeding\"\u003e\n    \u003cimg src=\"https://david-dm.org/w3tecch/typeorm-seeding/status.svg?style=flat\" alt=\"Dependency\" /\u003e\n  \u003c/a\u003e\n    \u003ca href=\"https://github.com/semantic-release/semantic-release\"\u003e\u003cimg src=\"https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg\" alt=\"Sematic-Release\" /\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cb\u003eA delightful way to seed test data into your database.\u003c/b\u003e\u003c/br\u003e\n  \u003cspan\u003eInspired by the awesome framework \u003ca href=\"https://laravel.com/\"\u003elaravel\u003c/a\u003e in PHP and of the repositories from \u003ca href=\"https://github.com/pleerock\"\u003epleerock\u003c/a\u003e\u003c/span\u003e\u003c/br\u003e\n  \u003csub\u003eMade with ❤️ by \u003ca href=\"https://github.com/hirsch88\"\u003eGery Hirschfeld\u003c/a\u003e and \u003ca href=\"https://github.com/w3tecch/typeorm-seeding/graphs/contributors\"\u003econtributors\u003c/a\u003e\u003c/sub\u003e\n\u003c/p\u003e\n\n\u003cbr /\u003e\n\n## ❯ Table of contents\n\n- [Introduction](#-introduction)\n- [Installation](#-installation)\n- [Basic Seeder](#-basic-seeder)\n- [Using Entity Factory](#-using-entity-factory)\n- [Seeding Data in Testing](#-seeding-data-in-testing)\n- [Changelog](#-changelog)\n- [License](#-license)\n\n## ❯ Introduction\n\nIsn't it exhausting to create some sample data for your database, well this time is over!\n\nHow does it work? Just create a entity factory for your entities (models) and a seed script.\n\n### Entity\n\nFirst create your TypeORM entities.\n\n```typescript\n// user.entity.ts\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn('uuid') id: string\n  @Column({ nullable: true }) name: string\n  @Column({ type: 'varchar', length: 100, nullable: false }) password: string\n  @OneToMany((type) =\u003e Pet, (pet) =\u003e pet.user) pets: Pet[]\n\n  @BeforeInsert()\n  async setPassword(password: string) {\n    const salt = await bcrypt.genSalt()\n    this.password = await bcrypt.hash(password || this.password, salt)\n  }\n}\n\n// pet.entity.ts\n@Entity()\nexport class Pet {\n  @PrimaryGeneratedColumn('uuid') id: string\n  @Column() name: string\n  @Column() age: number\n  @ManyToOne((type) =\u003e User, (user) =\u003e user.pets)\n  @JoinColumn({ name: 'user_id' })\n  user: User\n}\n```\n\n### Factory\n\nThen for each entity define a factory. The purpose of a factory is to create new entites with generate data.\n\n\u003e Note: Factories can also be used to generate data for testing.\n\n```typescript\n// user.factory.ts\ndefine(User, (faker: typeof Faker) =\u003e {\n  const gender = faker.datatype.number(1)\n  const firstName = faker.name.firstName(gender)\n  const lastName = faker.name.lastName(gender)\n\n  const user = new User()\n  user.name = `${firstName} ${lastName}`\n  user.password = faker.random.word()\n  return user\n})\n\n// pet.factory.ts\ndefine(Pet, (faker: typeof Faker) =\u003e {\n  const gender = faker.datatype.number(1)\n  const name = faker.name.firstName(gender)\n\n  const pet = new Pet()\n  pet.name = name\n  pet.age = faker.datatype.number()\n  pet.user = factory(User)() as any\n  return pet\n})\n```\n\n### Seeder\n\nAnd last but not least, create a seeder. The seeder can be called by the configured cli command `seed:run`. In this case it generates 10 pets with a owner (User).\n\n\u003e Note: `seed:run` must be configured first. Go to [CLI Configuration](#cli-configuration).\n\n```typescript\n// create-pets.seed.ts\nexport default class CreatePets implements Seeder {\n  public async run(factory: Factory, connection: Connection): Promise\u003cany\u003e {\n    await factory(Pet)().createMany(10)\n  }\n}\n```\n\nUntil [this issue](https://github.com/w3tecch/typeorm-seeding/issues/119) is closed, seeder files must not contain any other export statement besides the one that exports the seeder class.\n\n## ❯ Installation\n\nBefore using this TypeORM extension please read the [TypeORM Getting Started](https://typeorm.io/#/) documentation. This explains how to setup a TypeORM project.\n\nAfter that install the extension with `npm` or `yarn`.\n\n```bash\nnpm i typeorm-seeding\n# or\nyarn add typeorm-seeding\n```\n\nOptional, install the type definitions of the `Faker` library.\n\n```bash\nnpm install -D @types/faker\n```\n\n### Configuration\n\nTo configure the path to your seeds and factories change the TypeORM config file (ormconfig.js or ormconfig.json).\n\n\u003e The default paths are `src/database/{seeds,factories}/**/*{.ts,.js}`\n\n**ormconfig.js**\n\n```JavaScript\nmodule.exports = {\n  ...\n  seeds: ['src/seeds/**/*{.ts,.js}'],\n  factories: ['src/factories/**/*{.ts,.js}'],\n}\n```\n\n**.env**\n\n```\nTYPEORM_SEEDING_FACTORIES=src/factories/**/*{.ts,.js}\nTYPEORM_SEEDING_SEEDS=src/seeds/**/*{.ts,.js}\n```\n\n### CLI Configuration\n\nAdd the following scripts to your `package.json` file to configure the seed cli commands.\n\n```\n\"scripts\": {\n  \"seed:config\": \"ts-node ./node_modules/typeorm-seeding/dist/cli.js config\",\n  \"seed:run\": \"ts-node ./node_modules/typeorm-seeding/dist/cli.js seed\",\n  ...\n}\n```\n\nTo execute the seed run `npm run seed:run` in the terminal.\n\n\u003e Note: More CLI options are [here](#cli-options)\n\nAdd the following TypeORM cli commands to the package.json to drop and sync the database.\n\n```\n\"scripts\": {\n  ...\n  \"schema:drop\": \"ts-node ./node_modules/typeorm/cli.js schema:drop\",\n  \"schema:sync\": \"ts-node ./node_modules/typeorm/cli.js schema:sync\",\n  ...\n}\n```\n\n#### CLI Options\n\n| Option                 | Default         | Description                                                                 |\n| ---------------------- | --------------- | --------------------------------------------------------------------------- |\n| `--seed` or `-s`       | null            | Option to specify a seeder class to run individually.                       |\n| `--connection` or `-c` | null            | Name of the typeorm connection. Required if there are multiple connections. |\n| `--configName` or `-n` | `ormconfig.js`  | Name to the typeorm config file.                                            |\n| `--root` or `-r`       | `process.cwd()` | Path to the typeorm config file.                                            |\n\n## ❯ Basic Seeder\n\nA seeder class only contains one method by default `run`. Within this method, you may insert data into your database. For manually insertion use the [Query Builder](https://typeorm.io/#/select-query-builder) or use the [Entity Factory](#-using-entity-factory)\n\n\u003e Note. The seeder files will be executed alphabetically.\n\n```typescript\nimport { Factory, Seeder } from 'typeorm-seeding'\nimport { Connection } from 'typeorm'\nimport { User } from '../entities'\n\nexport default class CreateUsers implements Seeder {\n  public async run(factory: Factory, connection: Connection): Promise\u003cany\u003e {\n    await connection\n      .createQueryBuilder()\n      .insert()\n      .into(User)\n      .values([\n        { firstName: 'Timber', lastName: 'Saw' },\n        { firstName: 'Phantom', lastName: 'Lancer' },\n      ])\n      .execute()\n  }\n}\n```\n\n## ❯ Using Entity Factory\n\nOf course, manually specifying the attributes for each entity seed is cumbersome. Instead, you can use entity factories to conveniently generate large amounts of database records.\n\nFor all entities we want to create, we need to define a factory. To do so we give you the awesome [faker](https://github.com/marak/Faker.js/) 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`.\n\n| Types           | Description                                                                     |\n| --------------- | ------------------------------------------------------------------------------- |\n| `Entity`         | TypeORM Entity like the user or the pet in the samples.                          |\n| `Context`       | Argument to pass some static data into the factory function.                    |\n| `EntityFactory` | This object is used to make new filled entities or create it into the database. |\n\n### `define`\n\nThe define function creates a new entity factory.\n\n```typescript\ndefine: \u003cEntity, Context\u003e(entity: Entity, factoryFn: FactoryFunction\u003cEntity, Context\u003e) =\u003e void;\n```\n\n```typescript\nimport Faker from 'faker'\nimport { define } from 'typeorm-seeding'\nimport { User } from '../entities'\n\ndefine(User, (faker: typeof Faker, context: { roles: string[] }) =\u003e { ... })\n```\n\n### `factory`\n\nFactory retrieves the defined factory function and returns the EntityFactory to start creating new enities.\n\n```typescript\nfactory: (entity: Entity) =\u003e (context?: Context) =\u003e EntityFactory\u003cEntity, Context\u003e\n```\n\n```typescript\nfactory(Pet)()\nfactory(Pet)({ name: 'Balou' })\n```\n\n### EntityFactory\n\n#### `map`\n\nUse the `.map()` function to alter the generated value before they get persisted.\n\n```typescript\nmap(mapFunction: (entity: Entity) =\u003e Promise\u003cEntity\u003e): EntityFactory\u003cEntity, Context\u003e\n```\n\n```typescript\nawait factory(User)()\n  .map(async (user: User) =\u003e {\n    const pets: Pet[] = await factory(Pet)().createMany(2)\n    const petIds = pets.map((pet: Pet) =\u003e pet.Id)\n    await user.pets().attach(petIds)\n  })\n  .createMany(5)\n```\n\n#### `make` \u0026 `makeMany`\n\nMake and makeMany executes the factory functions and return a new instance of the given entity. The instance is filled with the generated values from the factory function, but not saved in the database.\n\n**overrideParams** - Override some of the attributes of the entity.\n\n```typescript\nmake(overrideParams: EntityProperty\u003cEntity\u003e = {}): Promise\u003cEntity\u003e\n```\n\n```typescript\nawait factory(User)().make()\nawait factory(User)().makeMany(10)\n\n// override the email\nawait factory(User)().make({ email: 'other@mail.com' })\nawait factory(User)().makeMany(10, { email: 'other@mail.com' })\n```\n\n#### `create` \u0026 `createMany`\n\nthe create and createMany method is similar to the make and makeMany method, but at the end the created entity instance gets persisted in the database.\n\n**overrideParams** - Override some of the attributes of the entity.\n**saveOptions** - [Save options](https://github.com/typeorm/typeorm/blob/master/src/repository/SaveOptions.ts) from typeorm\n\n```typescript\ncreate(overrideParams: EntityProperty\u003cEntity\u003e = {}, saveOptions?: SaveOptions): Promise\u003cEntity\u003e\ncreateMany(amount: number, overrideParams: EntityProperty\u003cEntity\u003e = {}, saveOptions?: SaveOptions): Promise\u003cEntity\u003e\n```\n\n```typescript\nawait factory(User)().create()\nawait factory(User)().createMany(10)\n\n// override the email\nawait factory(User)().create({ email: 'other@mail.com' })\nawait factory(User)().createMany(10, { email: 'other@mail.com' })\n\n// using save options\nawait factory(User)().create({ email: 'other@mail.com' }, { listeners: false })\nawait factory(User)().createMany(10, { email: 'other@mail.com' }, { listeners: false })\n```\n\n## ❯ Seeding Data in Testing\n\nThe entity factories can also be used in testing. To do so call the `useSeeding` function, which loads all the defined entity factories.\n\nChoose your test database wisley. We suggest to run your test in a sqlite in memory database.\n\n```json\n{\n  \"type\": \"sqlite\",\n  \"name\": \"memory\",\n  \"database\": \":memory:\"\n}\n```\n\nHowever, if the test database is not in memory, than use the `--runInBand` flag to disable parallelizes runs.\n\n```typescript\ndescribe(\"UserService\", () =\u003e {\n  let connection: Connection\n\n  beforeAll(async (done) =\u003e {\n    connection = await useRefreshDatabase({ connection: 'memory' })\n    await useSeeding()\n\n    const user = await factory(User)().make()\n    const createdUser = await factory(User)().create()\n\n    await runSeeder(CreateUserSeed)\n    done()\n  })\n\n  afterAll(async (done) =\u003e {\n    await tearDownDatabase()\n    done()\n  })\n\n  test('Should ...', () =\u003e { ... })\n})\n```\n\n### `useSeeding`\n\nLoads the defined entity factories.\n\n```typescript\nuseSeeding(options: ConfigureOption = {}): Promise\u003cvoid\u003e\n```\n\n### `runSeeder`\n\nRuns the given seeder class.\n\n```typescript\nrunSeeder(seed: SeederConstructor): Promise\u003cvoid\u003e\n```\n\n### `useRefreshDatabase`\n\nConnects to the database, drops it and recreates the schema.\n\n```typescript\nuseRefreshDatabase(options: ConfigureOption = {}): Promise\u003cConnection\u003e\n```\n\n### `tearDownDatabase`\n\nCloses the open database connection.\n\n```typescript\ntearDownDatabase(): Promise\u003cvoid\u003e\n```\n\n### `ConfigureOption`\n\n```typescript\ninterface ConfigureOption {\n  root?: string // path to the orm config file. Default = process.cwd()\n  configName?: string // name of the config file. eg. ormconfig.js\n  connection?: string // name of the database connection.\n}\n```\n\n## ❯ Example Projects\n\n\u003e Please fill free to add your open-source project here. This helps others to better understand the seeding technology.\n\n| Project                                                                                  | Description                                                                                                                    |\n| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| [copa-ch/copa-backend](https://github.com/copa-ch/copa-backend/tree/master/src/database) | 🚀 Nest application written in TypeScript for the COPA project. This app manages your tournaments and generates the schedules. |\n\n## ❯ Changelog\n\n[Changelog](https://github.com/w3tecch/typeorm-seeding/releases)\n\n## ❯ License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fw3tecch%2Ftypeorm-seeding","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fw3tecch%2Ftypeorm-seeding","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fw3tecch%2Ftypeorm-seeding/lists"}