nestjs-typeorm-seeding
v0.0.6
Published
🌱 A delightful way to seed test data into your database.
Downloads
9
Readme
Script
"db:migration": "ts-node bin/migration.cli.ts",
"db:migrate": "ts-node node_modules/typeorm/cli.js migration:run -d src/config/database.ts",
"db:entity": "ts-node bin/entity.cli.ts",
"db:seed": "ts-node bin/seed.cli.ts",
"db:factory": "ts-node bin/factory.cli.ts",
"db:seeding": "ts-node node_modules/nestjs-typeorm-seeding/cli.js seed -d src/config/database.ts",
"db:enum": "ts-node bin/enum.cli.ts"
Bin folder
entity.cli.js
import { execSync } from 'child_process';
import { replaceInFile } from 'replace-in-file';
const args: string[] = process.argv.slice(2);
if (args.length === 0) {
console.error('Please provide a entity name.');
process.exit(1);
}
const entityName: string = args[0];
try {
console.log('\u001b[44;37m Creating TypeORM entity... \u001b[0m');
execSync(`ts-node node_modules/typeorm/cli.js entity:create src/models/entities/${entityName}.entity`, { stdio: 'inherit' });
replaceInFile({
files: `src/models/entities/${entityName}.entity.ts`,
from: /\.entity/g,
to: '',
}).then();
console.log('\u001b[42;37m TypeORM entity created. \u001b[0m');
} catch (error) {
console.error('Error occurred while creating entity:', error);
process.exit(1);
}
enum.cli.js
import * as fs from 'fs-extra';
let args: string[];
args = process.argv.slice(2);
if (args.length === 0) {
console.error('Please provide a enum name.');
process.exit(1);
}
const factoryName: string = args[0];
const now: number = Date.now();
const fileName: string = `src/models/enum/${factoryName}.enum.ts`;
const data: string =
`export class ${factoryName.toUpperCase()} {
static KEY = "value";
private static values = new Map([
["key", 'value']
]);
static get(key: any) {
return this.values.get(key);
}
}
`;
try {
console.log("\u001b[44;37m Creating TypeORM factory... \u001b[0m");
console.log(`Creating enum name ${factoryName} ... `);
fs.writeFileSync(fileName, data);
console.log("\u001b[42;37m TypeORM enum created. \u001b[0m");
} catch (error) {
console.error('Error occurred while creating enum:', error);
process.exit(1);
}
factory.cli.js
import * as fs from 'fs-extra';
let args: string[];
args = process.argv.slice(2);
if (args.length === 0) {
console.error('Please provide a factory name.');
process.exit(1);
}
const factoryName: string = args[0];
const now: number = Date.now();
const fileName: string = `src/database/factories/${now}-${factoryName}.factory.ts`;
const data: string =
`import { faker } from '@faker-js/faker';
import { define } from 'nestjs-typeorm-seeding';
import { ${factoryName} } from '../../models/entities/${factoryName}';
define(${factoryName}, (): ${factoryName} => {
let ${factoryName.toLowerCase()}: ${factoryName};
${factoryName.toLowerCase()} = new ${factoryName}();
// logic goes here
return ${factoryName.toLowerCase()};
});
`;
try {
console.log("\u001b[44;37m Creating TypeORM factory... \u001b[0m");
console.log(`Creating factory for seed name ${factoryName} ... `);
fs.writeFileSync(fileName, data);
console.log("\u001b[42;37m TypeORM factory created. \u001b[0m");
} catch (error) {
console.error('Error occurred while creating factory:', error);
process.exit(1);
}
migration.cli.js
import { execSync } from 'child_process';
import { replaceInFile } from 'replace-in-file';
const args: string[] = process.argv.slice(2);
if (args.length === 0) {
console.error('Please provide a migration name.');
process.exit(1);
}
const migrationName: string = args[0];
try {
console.log("\u001b[44;37m Creating TypeORM migration... \u001b[0m");
execSync(`ts-node node_modules/typeorm/cli.js migration:create src/database/migrations/${migrationName}.migration`, { stdio: 'inherit' });
replaceInFile({
files: `src/database/migrations/*-${migrationName}.migration.ts`,
from: /\.migration/g,
to: '',
}).then();
console.log("\u001b[42;37m TypeORM migration created. \u001b[0m");
} catch (error) {
console.error('Error occurred while creating migration:', error);
process.exit(1);
}
seed.cli.js
import { execSync } from 'child_process';
import { replaceInFile } from 'replace-in-file';
const args: string[] = process.argv.slice(2);
if (args.length === 0) {
console.error('Please provide a seed name.');
process.exit(1);
}
const seedName: string = args[0];
try {
console.log("\u001b[44;37m Creating TypeORM seed... \u001b[0m");
execSync(`ts-node node_modules/nestjs-typeorm-seeding/cli.js create -f ${seedName} -d src/config/database.ts`, { stdio: 'inherit' });
replaceInFile({
files: `src/database/seeds/*-${seedName.toLowerCase()}.seed.ts`,
from: /@paranode\//g,
to: 'nestjs-',
}).then();
console.log("\u001b[42;37m TypeORM seed created. \u001b[0m");
} catch (error) {
console.error('Error occurred while creating seed:', error);
process.exit(1);
}
src/config/database.ts
const env: dotenv.DotenvParseOutput = dotenv.config().parsed;
const datasource: DataSource = new DataSource({
type: env.DB_CONNECTION as DatabaseType,
host: env.DB_HOST,
port: +env.DB_PORT,
username: env.DB_USERNAME,
password: env.DB_PASSWORD,
database: env.DB_DATABASE,
logging: true,
logger: new DatabaseLog(new ConfigService()),
synchronize: false,
migrations: ['src/database/migrations/*.ts'],
seeds: ['src/database/seeds/*.ts'],
factories: ['src/database/factories/*.ts'],
cli: {
seedsDir: 'src/database/seeds',
factoriesDir: 'src/database/factories',
migrationsDir: 'src/database/migrations',
},
entities: ['src/models/entities/*.ts'],
} as DataSourceOptions);
export default datasource;