add db seed handler

This commit is contained in:
liuyi 2025-06-21 15:05:39 +08:00
parent b9ac3e5f94
commit af46a76a9c
4 changed files with 71 additions and 0 deletions

View File

@ -2,3 +2,4 @@ export * from './migration.create.command';
export * from './migration.revert.command';
export * from './migration.generate.command';
export * from './migration.run.command';
export * from './seeder.command';

View File

@ -0,0 +1,36 @@
import { Arguments } from 'yargs';
import { CommandItem } from '@/modules/core/types';
import { SeederHandler } from '@/modules/database/commands/seeder.handler';
import { SeederArguments } from '@/modules/database/commands/types';
export const SeederCommand: CommandItem<any, SeederArguments> = async ({ configure }) => ({
command: ['db:seed', 'dbs'],
describe: 'Runs all seeds data.',
builder: {
clear: {
type: 'boolean',
alias: 'r',
describe: 'Clear which tables will truncated specified by seeder class.',
default: true,
},
connection: {
type: 'string',
alias: 'c',
describe: 'Connection name of typeorm to connect database.',
},
transaction: {
type: 'boolean',
alias: 't',
describe: 'If is seed data in transaction,default is true',
default: true,
},
ignorelock: {
type: 'boolean',
alias: 'i',
describe: 'Ignore seed lock and reset all seeds, not do it in production',
default: false,
},
} as const,
handler: async (args: Arguments<SeederArguments>) => SeederHandler(configure, args),
});

View File

@ -0,0 +1,29 @@
import chalk from 'chalk';
import { isNil } from 'lodash';
import ora from 'ora';
import { Configure } from '@/modules/config/configure';
import { panic } from '@/modules/core/helpers';
import { SeederOptions } from '@/modules/database/commands/types';
import { DBOptions } from '@/modules/database/types';
import { runSeeder } from '@/modules/database/utils';
export async function SeederHandler(configure: Configure, args: SeederOptions) {
const cname = args.connection ?? 'default';
const { connections = [] }: DBOptions = await configure.get<DBOptions>('database');
const dbConfig = connections.find(({ name }) => name === cname);
if (isNil(dbConfig)) {
await panic(`Database connection named ${cname} not exists!`);
}
const runner = dbConfig.seedRunner;
const spinner = ora('Start run seeder...');
try {
spinner.start();
await runSeeder(runner, args, spinner, configure, dbConfig);
spinner.succeed(`\n 👍 ${chalk.greenBright.underline(`Finished Seeding`)}`);
} catch (error) {
await panic({ spinner, message: `Run seeder failed`, error });
}
}

View File

@ -122,3 +122,8 @@ export interface SeederLoadParams {
*/
ignoreLock: boolean;
}
/**
*
*/
export type SeederArguments = TypeOrmArguments & SeederOptions;