json-to-typed
Version:
Build to-typed objects from JSON files.
49 lines (48 loc) • 1.92 kB
JavaScript
import fs from 'fs/promises';
import { promise as glob } from 'glob-promise';
class Cli {
static async gen(inGlob, outFile = 'json-to-typed.ts', className = 'Data') {
const fileTemplate = 'static readonly ["<PATH>"] = TypedJsonFile.fromDefaults("<PATH>", <JSON>);';
const files = await glob(inGlob);
const members = await Promise.all(files.map(async (file) => {
const json = await fs.readFile(file, 'utf8');
const data = JSON.parse(json);
return fileTemplate.replace(/<PATH>/g, file).replace('<JSON>', JSON.stringify(data));
}));
let result = '';
result += '// This file was generated by json-to-typed\n';
result += 'import { TypedJsonFile } from "json-to-typed";\n';
result += '\n';
result += `export class ${className} {\n`;
result += members.map(m => '\t' + m).join('\n');
result += '\n';
result += '}\n';
await fs.writeFile(outFile, result);
}
static async runInternal(args) {
if (args.length < 1)
throw new Error('Missing command');
switch (args[0]) {
case 'gen':
if (args.length < 2)
throw new Error('Missing glob pattern');
return Cli.gen(args[1], args[2], args[3]);
default:
throw new Error(`Unknown command: ${args[0]}`);
}
}
static async run() {
if (process.argv.length < 3) {
console.log('Usage: json-to-typed <command> <args>');
console.log('Commands:');
console.log(' gen <input-glob> [outFile] [className] - Generate TypedJsonFile classes');
return;
}
else {
await this.runInternal(process.argv.slice(2));
process.exit();
}
}
}
Cli.run();