'Seed permanent data in typeORM v.0.3.6 with DataSource
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.
Solution 1:[1]
I used "typeorm-seeding": "^1.6.1" and the following were the steps I took.
- 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}'],
}
- 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
}
- 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: "[email protected]", password },
{ firstName: 'Phantom', lastName: 'Lancer', email: "[email protected]", password},
])
.execute()
}
}
- With the command
npm run seed:runthen your seeder is done
You can check Typeorm Seeding Link for more information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 2mighty |
