@ztimson/momentum
Version:
Client library for momentum
100 lines (90 loc) • 3.09 kB
JavaScript
import fs from 'fs';
import {join} from 'path';
import {Momentum} from '../dist/index.mjs';
import {formatDate, kebabCase, pascalCase} from '@ztimson/utils';
import readline from 'readline';
import packageFile from '../package.json' with {type: 'json'};
function ask(prompt, hide = false) {
const rl = readline.createInterface({input: process.stdin, output: process.stdout, terminal: true});
return new Promise((resolve) => {
if (!hide) {
rl.question(prompt, (answer) => {
resolve(answer);
rl.close();
});
} else {
let input = '';
const onKeyPress = (char, key) => {
if (key && key.name === 'return') {
rl.input.setRawMode(false);
rl.input.removeListener('keypress', onKeyPress);
rl.close();
resolve(input);
} else {
if (key && key.name === 'backspace') {
if (input.length > 0) input = input.slice(0, -1);
} else {
input += char;
}
rl.output.write(`\r${prompt}${'*'.repeat(input.length)} `);
}
};
// Attach keypress event
rl.input.on('keypress', onKeyPress);
rl.input.setRawMode(true);
rl.input.resume();
rl.output.write(prompt);
}
});
}
// Main loop
(async () => {
try {
// Arguments
let [, , destination, url, username, password] = process.argv;
console.log(`Momentum v${packageFile.default.version}`);
let momentum;
// Login
do {
while (!url) url = await ask('URL: ');
while (!username) username = await ask('Username: ');
while (!password) password = await ask('Password: ', true);
if (!url.startsWith('http')) url = 'http://' + url;
momentum = new Momentum(url);
await momentum.auth.login(username, password)
.catch(err => {
url = username = password = '';
console.log('Failed to authenticate');
});
} while (!momentum?.auth.user);
console.log('Login Succeeded!\n');
if (!destination) destination = await ask('Destination (src/models): ');
if (!destination) destination = 'src/models';
let path = join(process.cwd(), destination);
if (!fs.existsSync(path)) fs.mkdirSync(path);
console.log('\nCollecting Schemas...');
const schemas = await momentum.schemas.read();
schemas.forEach(schema => {
const fileName = kebabCase(schema.path) + '.ts';
console.log(`Creating Model: ${schema.path} -> ${fileName}`);
const path = join(process.cwd(), destination, fileName);
fs.writeFileSync(path, `import {Formula, Link, Meta} from '@ztimson/momentum';
/**
* Generated by Momentum v${packageFile.default.version}
* Date: ${formatDate('YYYY-MM-DD')}
* Schema: ${schema.path}
* Description: ${schema.description}
*/
export interface ${pascalCase(schema.path)} extends Meta${schema.columns.length ? '' : ', Record<string, any>'} {
${schema.columns.map(column => `\t${column.readonly ? 'readonly ' : ''}${column.prop}${column.required ? ':' : '?:'} ${column.type};`).join('\n')}
}
`);
});
console.log('Done!');
process.exit();
} catch (err) {
console.error(`\n${err.stack || err.stackTrace || err.message || err.toString()}`);
process.exit(1);
}
})();