From the typeorm-seeding guide, I created some files below:
post.factory.ts
import { define } from 'typeorm-seeding';
import { Post } from '../../src/entity';
define(Post, (faker: typeof Faker) => {
return new Post({
id: faker.random.uuid(),
title: 'test',
body: 'test',
});
});
post.seed.ts
import { Factory, Seeder } from 'typeorm-seeding';
import { Connection } from 'typeorm';
import { Post } from '../../src/entity';
export default class PostSeeder implements Seeder {
public async run(factory: Factory, _connection: Connection): Promise<any> {
await factory(Post)().createMany(10);
}
}
When run npm run seed:run
, it caused an error:
❌ Could not save entity
QueryFailedError: null value in column "title" of relation "posts" violates not-null constraint
query: 'INSERT INTO "blog"."posts"("id", "title", "body", "created_at", "updated_at") VALUES (DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "title", "created_at", "updated_at"',
parameters: [],
detail: 'Failing row contains (111111111-2a7d-4316-9a85-4d38d6e3febb, null, null, 2022-11-26 03:28:54.895454, null).',
The seed script in package.json:
{
"name": "blog",
"version": "0.0.1",
"description": "Blog",
"main": "index.js",
"scripts": {
"seed:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js seed -c seed",
...
"dependencies": {
"typeorm-seeding": "^1.6.1",
...
The seed related ormconfig.js:
module.exports = [
{
name: 'seed',
type: 'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
schema: 'blog',
uuidExtension: 'pgcrypto',
synchronize: false,
logging: false,
entities: ['src/entity/index.ts'],
factories: ['database/factories/**/*.factory.ts'],
seeds: ['database/seeds/**/*.seed.ts'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'database/migrations',
},
},
It seems when run seed it can't get parameters from factory. Where is wrong?
You can use Typeorm-faker
Just type like this
const postMock = stubOne(Post);
MethodYouWantToTest(postMock);