geoshell
Version:
A CLI to fetch real-time geo-data from your terminal
137 lines (118 loc) • 3.33 kB
JavaScript
/**
* Output formatting utilities
*/
const Table = require('cli-table3');
const chalk = require('chalk');
/**
* Format output based on format type
*
* @param {Object|Array} data - Data to format
* @param {string} format - Format type: json, table, csv
* @returns {string} Formatted output
*/
function formatOutput(data, format = 'json') {
switch (format.toLowerCase()) {
case 'table':
return formatAsTable(data);
case 'csv':
return formatAsCSV(data);
case 'json':
default:
return formatAsJSON(data);
}
}
/**
* Format data as JSON
*
* @param {Object|Array} data - Data to format
* @returns {string} JSON string
*/
function formatAsJSON(data) {
return JSON.stringify(data, null, 2);
}
/**
* Format data as table
*
* @param {Object|Array} data - Data to format
* @returns {string} Table string
*/
function formatAsTable(data) {
if (!data) {
return 'No data available';
}
// Handle array of objects
if (Array.isArray(data)) {
if (data.length === 0) {
return 'No data available';
}
const headers = Object.keys(data[0]);
const table = new Table({
head: headers.map(h => chalk.bold(h)),
chars: {
'top': '═', 'top-mid': '╤', 'top-left': '╔', 'top-right': '╗',
'bottom': '═', 'bottom-mid': '╧', 'bottom-left': '╚', 'bottom-right': '╝',
'left': '║', 'left-mid': '╟', 'mid': '─', 'mid-mid': '┼',
'right': '║', 'right-mid': '╢', 'middle': '│'
}
});
data.forEach(row => {
table.push(headers.map(header => {
const value = row[header];
return value === undefined ? '' : String(value);
}));
});
return table.toString();
}
// Handle single object
const table = new Table();
Object.entries(data).forEach(([key, value]) => {
const row = {};
row[chalk.bold(key)] = value === undefined ? '' : String(value);
table.push(row);
});
return table.toString();
}
/**
* Format data as CSV
*
* @param {Object|Array} data - Data to format
* @returns {string} CSV string
*/
function formatAsCSV(data) {
if (!data) {
return '';
}
// Handle array of objects
if (Array.isArray(data)) {
if (data.length === 0) {
return '';
}
const headers = Object.keys(data[0]);
let csv = headers.join(',') + '\n';
data.forEach(row => {
csv += headers.map(header => {
const value = row[header];
if (value === undefined || value === null) {
return '';
}
// Quote strings with commas
const stringValue = String(value);
return stringValue.includes(',') ? `"${stringValue}"` : stringValue;
}).join(',') + '\n';
});
return csv;
}
// Handle single object
let csv = 'Property,Value\n';
Object.entries(data).forEach(([key, value]) => {
const stringValue = value === undefined || value === null ? '' : String(value);
csv += `${key},${stringValue.includes(',') ? `"${stringValue}"` : stringValue}\n`;
});
return csv;
}
module.exports = {
formatOutput,
formatAsJSON,
formatAsTable,
formatAsCSV
};