Seed permanent data in typeORM v.0.3.6 with DataSource

Viewed 1250

Is there a simple way to seed data in typeORM v.0.3.6 with DataSource ? typeorm-seeding seems to use Connection which is deprecated.

3 Answers

Found this package https://www.npmjs.com/package/typeorm-extension

It has seeding feature and supports typeorm 0.3.x

Simple seed example:

import { Seeder, SeederFactoryManager } from 'typeorm-extension';
import { DataSource } from 'typeorm';
import { CategoryEntity } from 'src/entities/category.entity';

export default class CategorySeeder implements Seeder {
    public async run(
        dataSource: DataSource,
        factoryManager: SeederFactoryManager
    ): Promise<any> {
        const repository = dataSource.getRepository(CategoryEntity);
        await repository.insert([
          {
            name: "Cats"
          },
          {
            name: "Dogs"
          }
        ]);
    }
}

run seeds with npx typeorm-extension seed

I've just solved the same issue. So, you need to create one more connection in your config file through the DataSource (if you already connected through DataSource, than no need), my DataSource connection looks like this:

export const MigrationAppDataSource = new DataSource({
    type: "postgres",
    host: process.env.DB_HOST,
    port: parseInt(process.env.DB_PORT),
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    entities: ["../**/*.entity.ts"],
    migrations: ["dist/migrations/*{.ts,.js}"],
    synchronize: false,
});

Also have to mention: you have to set synchronize to false in both connections (if you have 2+ ofc).

The next step is try to create simple migration. My package.json snippet for creating a simple seed-migration:

"typeorm": "typeorm-ts-node-commonjs",
"db:createMigration": "typeorm migration:create",

Remember to enter a path for seed-migration, so your code should look like this:

npm run db:createMigration src/migrations/SeedName

If everything is cool, then you have to change the timestamp of this migration and insert the seed data you need with SQL code mine is:

export class Seed2617378125500 implements MigrationInterface {
    name = "Seed2617378125500";

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `INSERT INTO package_entity (id, created_at, name, description, price) VALUES(1, '20062022', 'Creative Direction', '', '450')`,
        );
        await queryRunner.query(
            `INSERT INTO project_type (id, created_at, name) VALUES(1, '20062022', 'Animation')`,
        );
        await queryRunner.query(
            `INSERT INTO project_type_packages_package_entity ("projectTypeId", "packageEntityId") VALUES(1, 3)`,
        );
        await queryRunner.query(
            `INSERT INTO project_type_packages_package_entity ("projectTypeId", "packageEntityId") VALUES(1, 4)`,
        );
        await queryRunner.query(
            `INSERT INTO project_type_packages_package_entity ("projectTypeId", "packageEntityId") VALUES(1, 5)`,
        );
        await queryRunner.query(
            `INSERT INTO project_type_packages_package_entity ("projectTypeId", "packageEntityId") VALUES(1, 6)`,
        );
        await queryRunner.query(
            `INSERT INTO project_type_packages_package_entity ("projectTypeId", "packageEntityId") VALUES(1, 11)`,
        );
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`DELETE * FROM project_type`);
        await queryRunner.query(`DELETE * FROM package_entity`);
    }
}

TIP: My seed is including the many-to-many connection and i was struggling trying to understand how to pass values in many-to-many connection columns. So you need to pass values in middle-table, which is created during initialization of your connected columns.

The next step for me is generate initial migration to create DB itslef:

"db:migrate": "npm run build && node --require ts-node/register ./node_modules/typeorm/cli.js -d src/config/configuration.ts migration:generate",

Remember to provide the same path as your seed-migration:

npm run db:migrate src/migrations/MigrationName

Also have to mention: you have to provide -d path/to/configWithDataSource in the command generating migrations and the command running migrations.

When my initial generation is generated and seeds are also done, i simply run a command to run migrations (you don't need to enter the path there, because it takes path from your DataSource file), mine:

"db:migrationRun": "npm run build && npx typeorm-ts-node-commonjs migration:run -d src/config/configuration.ts"

Enjoy! If you have some questions - feel free to ask me :)

I used "typeorm-seeding": "^1.6.1" and the following were the steps I took.

  1. Create an ormconfig.ts file with the content below
require('dotenv').config();

module.exports = {
    type: "postgres",
    host: process.env.DB_HOST,
    port: 5432,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    entities: ["src/db/entities/**/*.ts"],
    seeds: ['src/db/seeds/**/*{.ts,.js}'],
    factories: ['src/db/factories/**/*{.ts,.js}'],
}
  1. You have your entity defined in src/db/entities according to the above ormconfig.ts and assuming you have your User.ts entity defined there with the following content

@Entity()
export class User {

    @PrimaryGeneratedColumn("uuid")
    id: string

    @Column()
    firstName: string

    @Column()
    lastName: string

    @IsEmail()
    @Column({
        unique: true,
    })
    email: string

    @Column()
    password: string
}
  1. Create your seeder file src/db/seeds/createUser.ts
import { Factory, Seeder } from 'typeorm-seeding'
import { DataSource } from 'typeorm'
import { User } from '../entities/User'
import * as bcrypt from "bcrypt"

export default class CreateUsers implements Seeder {
    public async run(factory: Factory, datasource: DataSource): Promise<any> {
        const salt = 10
        const password = await bcrypt.hash("password", salt)
        await datasource
            .createQueryBuilder()
            .insert()
            .into(User)
            .values([
                { firstName: 'Timber', lastName: 'Saw', email: "example@gmail.com", password },
                { firstName: 'Phantom', lastName: 'Lancer', email: "example@gmail.com", password},
            ])
            .execute()
    }
}
  1. With the command npm run seed:run then your seeder is done

You can check Typeorm Seeding Link for more information.

Related