NodeJS 如何通过typeorm-seeding使用工厂创建faker数据?

xghobddn  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(114)

根据typeorm-seeding指南,我创建了下面的一些文件:

  • database/factories/post.factory.ts
  • database/seeds/post.seed.ts

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);
  }
}


当运行npm run seed:run时,它导致了一个错误:

❌  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).',


package.json中的seed脚本:

{
  "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",
    ...


种子相关的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',
    },
  },


运行seed时似乎无法从工厂获取参数。哪里错了?

mtb9vblg

mtb9vblg1#

可以使用Typeorm-faker
就像这样打字

const postMock = stubOne(Post);

MethodYouWantToTest(postMock);

字符串

相关问题