Skip to content

Instantly share code, notes, and snippets.

@sigmasoldi3r
Created February 12, 2018 14:41
Show Gist options
  • Save sigmasoldi3r/eaa2a2a4c296c23eb3e4681a9af238a2 to your computer and use it in GitHub Desktop.
Save sigmasoldi3r/eaa2a2a4c296c23eb3e4681a9af238a2 to your computer and use it in GitHub Desktop.
Regenerates entity repositories when using TypeORM
#!/home/lenovo/.node/bin/node
/**
* Regenrates the default repositories given a model.
*/
const fs = require('fs');
const program = require('commander');
const path = require('path');
const author = 'Pablo Blanco Celdran';
program
.version('0.0.1')
.arguments('<model>')
.option('-f, --force', 'Overwrites repository files even if they exist.')
.option('-o, --out [output dir]', 'Specifies the output directory, defaults to cwd.')
.parse(process.argv);
if (!program.args.length) {
console.error('Missing model argument: Specify the input folder!');
program.help();
process.exit(-1);
}
const output = program.out || './';
const input = program.args[0];
const list = fs.readdirSync(path.normalize(input));
function writef(entity, repo, input, output) {
fs.writeFileSync(path.join(output, repo) + '.ts', `import { EntityRepository, Repository } from 'typeorm';
import { ${entity} } from '${path.join(input, entity)}';
/**
* ${repo} Repository for entity ${entity}.
* This file was generated automagically.
* @author ${author}
* @created ${new Date().toDateString()}
*/
@EntityRepository(${entity})
export class ${repo} extends Repository<${entity}> {
}`);
}
function formatRepoName(repoName, root) {
return ` - File ${path.join(root, repoName)}.ts`;
}
function report(repoName, output, err) {
console.log(`${formatRepoName(repoName, output)} raised an error, skipping... (${err.message})`);
}
let written = 0, skipped = 0;
for (const entity of list) {
const entityName = entity.replace('.ts', '').trim();
const repoName = `${entityName}Repository`;
try {
const stat = fs.statSync(path.join(output, repoName) + '.ts');
if (program.force) {
try {
writef(entityName, repoName, input, output);
written++;
console.log(`${formatRepoName(repoName, output)} already exists, overwriting...`);
} catch (err) {
skipped++;
report(repoName, output, err);
}
} else {
skipped++;
console.log(`${formatRepoName(repoName, output)} already exists, skipping...`);
}
} catch (err) {
try {
writef(entityName, repoName, input, output);
written++;
console.log(`${formatRepoName(repoName, output)} created.`);
} catch (err) {
skipped++;
report(repoName, output, err);
}
}
}
console.log(`Done! Total: ${list.length}, skipped ${skipped} and written ${written} files.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment