@onurege3467/zerohelper
Version:
ZeroHelper is a versatile high-performance utility library and database framework for Node.js, fully written in TypeScript.
124 lines (123 loc) • 5.44 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.importCommand = exports.exportCommand = void 0;
const commander_1 = require("commander");
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const config_1 = require("../utils/config");
const prompts_1 = require("../utils/prompts");
exports.exportCommand = new commander_1.Command().name('db');
exports.exportCommand
.command('export')
.description('Export table data to file')
.option('-c, --config <path>', 'Path to config file', 'zero.config.ts')
.option('-t, --table <name>', 'Table name to export')
.option('-f, --format <format>', 'Output format (json|csv)', 'json')
.option('-o, --output <file>', 'Output file path')
.action(async (options) => {
if (!options.table) {
console.error(chalk_1.default.red('Error: --table option is required'));
process.exit(1);
}
const spinner = (0, ora_1.default)(`Exporting ${options.table}...`).start();
try {
const db = await (0, config_1.getDatabase)(options.config);
const records = await db.select(options.table);
if (records.length === 0) {
spinner.warn(chalk_1.default.yellow(`⚠️ No records found in ${options.table}`));
await db.close();
return;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const ext = options.format === 'csv' ? 'csv' : 'json';
const defaultFile = `${options.table}_export_${timestamp}.${ext}`;
const outputFile = options.output || path_1.default.join(process.cwd(), 'exports', defaultFile);
const outputDir = path_1.default.dirname(outputFile);
if (!fs_1.default.existsSync(outputDir)) {
fs_1.default.mkdirSync(outputDir, { recursive: true });
}
let content = '';
if (options.format === 'csv') {
const headers = Object.keys(records[0]);
const csvRows = [
headers.join(','),
...records.map((row) => headers.map(h => {
const val = row[h];
return typeof val === 'string' && val.includes(',') ? `"${val}"` : val;
}).join(','))
];
content = csvRows.join('\n');
}
else {
content = JSON.stringify(records, null, 2);
}
fs_1.default.writeFileSync(outputFile, content);
const fileSize = fs_1.default.statSync(outputFile).size;
spinner.succeed(chalk_1.default.green(`✅ Exported ${records.length} records to ${outputFile}`));
console.log(chalk_1.default.gray(` Size: ${(0, config_1.formatBytes)(fileSize)}`));
console.log(chalk_1.default.gray(` Format: ${options.format.toUpperCase()}`));
await db.close();
}
catch (error) {
spinner.fail(chalk_1.default.red('❌ Export failed'));
console.error(chalk_1.default.red(error.message));
process.exit(1);
}
});
exports.importCommand = new commander_1.Command().name('db');
exports.importCommand
.command('import')
.description('Import data from file to table')
.argument('<file>', 'Input file path')
.option('-c, --config <path>', 'Path to config file', 'zero.config.ts')
.option('-t, --table <name>', 'Table name')
.option('-f, --format <format>', 'Input format (json|csv)', 'json')
.action(async (inputFile, options) => {
if (!options.table) {
console.error(chalk_1.default.red('Error: --table option is required'));
process.exit(1);
}
if (!fs_1.default.existsSync(inputFile)) {
console.error(chalk_1.default.red(`Error: File not found: ${inputFile}`));
process.exit(1);
}
const confirmed = await (0, prompts_1.confirmAction)(chalk_1.default.yellow(`⚠️ This will import data to ${options.table}. Are you sure?`));
if (!confirmed) {
console.log(chalk_1.default.yellow('Import cancelled'));
return;
}
const spinner = (0, ora_1.default)(`Importing to ${options.table}...`).start();
try {
const db = await (0, config_1.getDatabase)(options.config);
const content = fs_1.default.readFileSync(inputFile, 'utf-8');
let data = [];
if (options.format === 'csv') {
const lines = content.trim().split('\n');
const headers = lines[0].split(',');
data = lines.slice(1).map((line) => {
const values = line.split(',');
const row = {};
headers.forEach((h, i) => {
row[h] = values[i]?.replace(/"/g, '').trim();
});
return row;
});
}
else {
data = JSON.parse(content);
}
const count = await db.bulkInsert(options.table, data);
spinner.succeed(chalk_1.default.green(`✅ Imported ${count} records to ${options.table}`));
await db.close();
}
catch (error) {
spinner.fail(chalk_1.default.red('❌ Import failed'));
console.error(chalk_1.default.red(error.message));
process.exit(1);
}
});