UNPKG

@pradyumn-el/pollycli

Version:

pollycli lets users access the functionalities of Polly over a command line interface

111 lines (92 loc) 2.47 kB
const chalk = require('chalk'); const table = require('table'); const fs = require('fs'); const path = require('path'); export function pollySuccess(message) { console.log(chalk.green.bold(`Success: ${message}`)); } export function pollyError(message) { console.log(chalk.red.bold(`Error: ${message}`)); process.exit(1); } export function pollyErrorNoExit(message) { console.log(chalk.red.bold(`Error: ${message}`)); } export function pollyMessage(message) { console.log(chalk.green.bold(`${message}`)); } export function pollyTable(data, from = 1, to = data.length, tableConfig = null) { if (from < 1) { from = 1; } if (to > data.length) { to = data.length; } let tableHeaders = chalk.green.bold(data[0]).split(","); const dataMatrix = data.splice(from, to - from + 1); let message = null; if ( global.outputFormat && global.outputFormat.format === 'json' ) { fs.writeFileSync(path.resolve(global.outputFormat.path), JSON.stringify(arrayToJSONObject([...data, ...dataMatrix]), null, ' ')); } else if ( tableConfig == null ) { message = table.table([tableHeaders, ...dataMatrix]); } else { message = table.table([tableHeaders, ...dataMatrix], tableConfig); } if (message) { console.log(message); } } function arrayToJSONObject(arr) { //header const keys = []; for (const key of arr[0]) { keys.push(key.trim().replace(/ /g,"_").toLowerCase()); } //vacate keys from main array const newArr = arr.slice(1, arr.length); let formatted = [], data = newArr, cols = keys, l = cols.length; for (let i = 0; i < data.length; i++) { const d = data[i], o = {}; for (let j = 0; j < l; j++) { if(isJson(d[j])) { o[cols[j]] = JSON.parse(d[j]); } else { o[cols[j]] = d[j]; } } formatted.push(o); } return formatted; } export function pollyStreamTable(stream, dataOneByOne, colConfig = {}) { if (!stream) { const config = { columnDefault: { width: 25 }, columns: colConfig, columnCount: dataOneByOne.length }; stream = table.createStream(config); } stream.write(dataOneByOne); return stream; } function isJson(item) { item = typeof item !== "string" ? JSON.stringify(item) : item; try { item = JSON.parse(item); } catch (e) { return false; } if (typeof item === "object" && item !== null) { return true; } return false; }