TypeORM Extension Library

3.9.0 · active · verified Wed Apr 22

typeorm-extension is a robust library that augments TypeORM with essential database management functionalities, including streamlined database creation and dropping, and a powerful, flexible data seeding mechanism. It integrates seamlessly with the TypeORM ecosystem, offering CLI commands for many of its operations. Currently at version 3.9.0, the library maintains an active release cadence, frequently introducing minor features and critical bug fixes. Its key differentiators lie in simplifying complex database setup and teardown, as well as providing sophisticated factory-based data seeding capabilities, which are especially useful for development, testing, and populating initial datasets. It acts as a significant convenience layer over raw TypeORM operations for these specific use cases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a TypeORM DataSource, define an entity, set up a SeederFactory for generating fake data with `@faker-js/faker`, and then execute a custom Seeder to populate the database. It includes creating and dropping the schema for a clean run.

import { DataSource, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { createDataSource, runSeeder, Seeder, SeederFactory, setSeederFactory } from 'typeorm-extension';
import { faker } from '@faker-js/faker';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  firstName!: string;

  @Column()
  lastName!: string;

  @Column({ unique: true })
  email!: string;
}

// 1. Define a SeederFactory
setSeederFactory(User, (faker) => {
  const user = new User();
  user.firstName = faker.person.firstName();
  user.lastName = faker.person.lastName();
  user.email = faker.internet.email().toLowerCase();
  return user;
});

// 2. Create a Seeder class
class UserSeeder implements Seeder {
  async run(dataSource: DataSource): Promise<any> {
    const repository = dataSource.getRepository(User);

    const users = await Promise.all(
      Array(10)
        .fill(null)
        .map(() => setSeederFactory(User)(faker).make())
    );
    await repository.save(users);
    console.log(`Seeded ${users.length} users.`);
  }
}

// 3. Main execution function
async function bootstrap() {
  // Create a new DataSource connection
  const dataSource = await createDataSource({
    type: 'sqlite',
    database: './temp_db.sqlite',
    entities: [User],
    synchronize: true, // Automatically create schema for demo
    logging: false,
    dropSchema: true // Drop schema to ensure a clean state for demo
  });

  if (!dataSource) {
    throw new Error('DataSource not initialized');
  }

  console.log('DataSource created and connected.');

  try {
    // Run the seeder
    await runSeeder(dataSource, UserSeeder);
    console.log('Seeding complete.');
  } catch (error) {
    console.error('Seeding failed:', error);
  } finally {
    // Ensure the data source is closed
    if (dataSource.isInitialized) {
      await dataSource.destroy();
      console.log('DataSource destroyed.');
    }
  }
}

bootstrap().catch(console.error);

view raw JSON →