@elucidatainc/pollycli
Version:
pollycli lets users access the functionalities of Polly over a command line interface
89 lines (77 loc) • 2.51 kB
JavaScript
const{ authApi } = require('./api-client');
const pollymsg = require('./message');
export function formatBytes(bytes, decimals = 3) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export function handleApiError(error, message="") {
let err_msg = ""
if (error.code == "EAI_AGAIN") {
err_msg = "please check your internet connection"
if(message) {
err_msg = message +", " + err_msg;
}
}
if(error.response && error.response.status && error.response.data.errors) {
err_msg = error.response.data.errors[0].detail;
}
if(err_msg) {
pollymsg.pollyError(err_msg);
}
}
export async function formatJobStatusReason(jobStatusReason) {
// 70 is the char limit for single line that we set, more than that
// in a single line might overflow chars to next line without \n
// resulting in a distorted cli interphase
let charLimit = 70;
if (jobStatusReason.length > charLimit){
let start = 0;
let end = charLimit;
let tempReason = ""
while (end < jobStatusReason.length){
tempReason = tempReason.concat(jobStatusReason.slice(start,end));
tempReason = tempReason.concat("\n");
start+=charLimit;
end+=charLimit;
}
tempReason = tempReason.concat(jobStatusReason.slice(start,end));
jobStatusReason = tempReason;
}
return jobStatusReason;
}
export async function getUserInfo() {
try {
const response = await authApi.get('/users/me')
return response.data;
} catch {
pollymsg.pollyError("Not able to get user details.");
}
}
export async function generateApiKey(name, description, expiry_date) {
try {
const userInfo = await getUserInfo();
const apiKeyUrl = `/users/${userInfo.data.id}/apikeys`;
const apiKeyPayload = {
"data": {
"attributes": {
name,
description,
expiry_date
},
"type": "user_apikey"
}
}
let response = await authApi.post(apiKeyUrl, apiKeyPayload)
response = response.data;
return response.data.attributes.secret_key;
} catch(e) {
pollymsg.pollyError("Not able to generate api key");
}
}
export function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}