Skip to content

Commit

Permalink
added minimal table, refactored code, added changelog, version 0.5.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sagarkarira committed Mar 19, 2020
1 parent 66bd918 commit a6e12a5
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 66 deletions.
50 changes: 36 additions & 14 deletions app.js
Expand Up @@ -2,17 +2,21 @@ const express = require('express');
const app = express();
const lookup = require('country-code-lookup');
const morgan = require('morgan');
const stripAnsi = require('strip-ansi');

const port = process.env.PORT || 3001;

const { getCountryTable, getJSONData, getJSONDataForCountry } = require('./lib/byCountry');
const { getCompleteTable } = require('./lib/corona');
const { countryUpperCase, lookupCountry } = require('./lib/helpers');
const { lookupCountry } = require('./lib/helpers');


function errorHandler(error, res) {
console.error(error);
return res.send('I am sorry. Something went wrong. Please report it');
return res.send(`
I am sorry. Something went wrong. Please report it \n
${error.message}
`);
}

app.use(morgan(':remote-addr :remote-user :method :url :status :res[content-length] - :response-time ms'));
Expand All @@ -21,37 +25,54 @@ app.use((req, res, next) => {
next();
});


+app.get('/updates', (req, res) => {
const format = req.query.format ? req.query.format : '';
if (format.toLowerCase() === 'json') {
return getLiveUpdates(true).then(result => {
return res.json(result);
}).catch(error => errorHandler(error, res));
}
return getLiveUpdates(false).then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
});

app.get('/', (req, res) => {
const isCurl = req.headers['user-agent'].match(/\bcurl\b/gmi) !== null;
const format = req.query.format ? req.query.format : '';
const minimal = req.query.minimal === 'true' ? true : false;
const emojis = req.query.emojis === 'true' ? true : false;

if (format.toLowerCase() === 'json') {
return getJSONData().then(result => {
return res.json(result);
}).catch(error => errorHandler(error, res));
}

return getCompleteTable({ isCurl }).then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
return getCompleteTable({ isCurl, emojis, minimal })
.then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
});

app.get('/:country', (req, res) => {
const { country } = req.params;
const isCurl = req.headers['user-agent'].match(/\bcurl\b/gmi) !== null;
const format = req.query.format ? req.query.format : '';

const minimal = req.query.minimal === 'true' ? true : false;
const emojis = req.query.emojis === 'true' ? true : false;
if (!country || 'ALL' === country.toUpperCase()) {
if (format.toLowerCase() === 'json') {
return getJSONData().then(result => {
return res.json(result);
}).catch(error => errorHandler(error, res));
}


return getCompleteTable({ isCurl }).then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
return getCompleteTable({ isCurl, emojis, minimal })
.then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
}

let lookupObj = lookupCountry(country);
Expand All @@ -63,7 +84,7 @@ app.get('/:country', (req, res) => {
Ex:
- /UK: for United Kingdom
- /US: for United States of America.
- /India: for India.
- /Italy: for Italy.
`);
}

Expand All @@ -75,9 +96,10 @@ app.get('/:country', (req, res) => {
}).catch(error => errorHandler(error, res));
}

return getCountryTable({ countryCode: iso2, isCurl }).then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
return getCountryTable({ countryCode: iso2, isCurl, emojis, minimal })
.then(result => {
return res.send(result);
}).catch(error => errorHandler(error, res));
});


Expand Down
14 changes: 10 additions & 4 deletions bin/index.js
Expand Up @@ -7,7 +7,7 @@ const { getCountryTable } = require('../lib/byCountry');
const { lookupCountry } = require('../lib/helpers');

const { argv } = yargs
.command('$0 [country]','Tool to track COVID-19 statistics for the world or the given country', yargs =>
.command('$0 [country]','Tool to track COVID-19 statistics from terminal', yargs =>
yargs.positional('country', {
coerce(arg) {
if ('ALL' === arg.toUpperCase()) {
Expand Down Expand Up @@ -41,16 +41,22 @@ const { argv } = yargs
alias: 'color',
describe: 'Show colors formatted output',
type: 'boolean'
},
m: {
alias: 'minimal',
describe: 'remove borders and padding from table',
type: 'boolean',
default: false,
}
})
.strict()
.help('help');

const { emojis, country } = argv;
const { emojis, country, minimal } = argv;
(
country === 'ALL'
? getCompleteTable({emojis})
: getCountryTable({ countryCode: country, emojis })
? getCompleteTable({ emojis, minimal })
: getCountryTable({ countryCode: country, emojis, minimal })
)
.then(console.log)
.catch(console.error);
22 changes: 22 additions & 0 deletions changelog.md
@@ -0,0 +1,22 @@
# Changelog

## Version 0.5.0

* Added minimal / comapct table command. ``corona --minimal``
* Added world total stats at the bottom of the table too.
* Refactor: moved table formatting functions to helpers.
* Added total stats object when using `?format=json`

## Version 0.4.0

* Added country filter. Ex: ``corona Italy``
* Added command to show emojis. Ex: ``corona --emojis``
* Added command to disable colors using. Ex: ``corona --color=false``

## Version 0.2.0

* Added daily and weekly column.

## Version 0.1.0

* Lauched command `corona`
39 changes: 15 additions & 24 deletions lib/byCountry.js
Expand Up @@ -69,7 +69,9 @@ exports.getJSONData = async () => {
const data = await api.getCoronaData();
const { latest, confirmed, deaths, recovered } = data;
const countryData = getDataByState(confirmed, deaths, recovered);
return countryData;
const totalStats = getTotalStats(countryData);
totalStats.country = 'World';
return countryData.concat(totalStats);
}

exports.getJSONDataForCountry = async (countryCode) => {
Expand All @@ -80,27 +82,16 @@ exports.getJSONDataForCountry = async (countryCode) => {
return countryData;
}

exports.getCountryTable = async ({countryCode, emojis = false, isCurl = true}) => {
const head = [
'',
'State',
'Confirmed',
`Recovered${emojis ? ' 😀' : ''}`,
`Deaths${emojis ? ' 😞' : ''}`,
`Active${emojis ? ' 😷' : ''}`,
'Mortality %',
'Recovered %',
'1 Day ▲',
'1 Week ▲',
// 'RoG',
...( emojis ? ['🏳'] : [] ),
];
exports.getCountryTable = async ({
countryCode,
emojis = false,
isCurl = true,
minimal = false,
}) => {
const table = new Table({
head,
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': '│' }
head: helpers.getTableHeaders(emojis, 'State'),
chars: helpers.getTableBorders(minimal),
style: helpers.getTableStyles(minimal),
});
const data = await api.getCoronaData();
const { latest, confirmed, deaths, recovered } = data;
Expand Down Expand Up @@ -167,9 +158,9 @@ exports.getCountryTable = async ({countryCode, emojis = false, isCurl = true}) =
}
</style>
</head>
<body>
<pre>${table.toString() + footer(lastUpdated)}</pre>
</body>
<body>
<pre>${table.toString() + footer(lastUpdated)}</pre>
</body>
</html>`;
return stripAnsi(template);
}
Expand Down
49 changes: 26 additions & 23 deletions lib/corona.js
Expand Up @@ -80,27 +80,15 @@ function extraStats(dataArr) {
);
}

exports.getCompleteTable = async ({isCurl = true, emojis = false}) => {
const head = [
'',
'Country',
`Confirmed ${emojis ? ' ✅': ''}`,
`Recovered${emojis ? ' 😀' : ''}`,
`Deaths${emojis ? ' 😞' : ''}`,
`Active${emojis ? ' 😷' : ''}`,
'Mortality %',
'Recovered %',
'1 Day ▲',
'1 Week ▲',
// 'RoG',
...( emojis ? ['🏳'] : [] ),
];
exports.getCompleteTable = async ({
isCurl = true,
emojis = false,
minimal = false,
}) => {
const table = new Table({
head,
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': '│' }
head: helpers.getTableHeaders(emojis, 'Country'),
chars: helpers.getTableBorders(minimal),
style: helpers.getTableStyles(minimal),
});
const data = await api.getCoronaData();
const { latest, confirmed, deaths, recovered } = data;
Expand Down Expand Up @@ -139,6 +127,21 @@ exports.getCompleteTable = async ({isCurl = true, emojis = false}) => {
]
table.push({ [rank++]: values })
});
table.push({
'': [
'World',
getConfirmed(worldStats.confirmed),
getRecovered(worldStats.recovered),
getDeaths(worldStats.deaths),
getActive(worldStats.active),
getMortalityPer(worldStats.mortalityPer),
getRecoveredPer(worldStats.recoveredPer),
getOneDayChange(worldStats),
getOneWeekChange(worldStats),
// '',
...( emojis ? ['🌎'] : [] )
]
})
const lastUpdated = countryData[0].lastUpdated;
if (!isCurl) {
const template = `<!DOCTYPE html>
Expand All @@ -159,9 +162,9 @@ exports.getCompleteTable = async ({isCurl = true, emojis = false}) => {
}
</style>
</head>
<body>
<pre>${table.toString() + footer(lastUpdated)}</pre>
</body>
<body>
<pre>${table.toString() + footer(lastUpdated)}</pre>
</body>
</html>`
return stripAnsi(template);
}
Expand Down
37 changes: 37 additions & 0 deletions lib/helpers.js
Expand Up @@ -174,3 +174,40 @@ Twitter: https://twitter.com/ekrysis
Last Updated on: ${moment(lastUpdated).utc().format('DD-MMM-YYYY HH:MM')} UTC
`;

e.getTableBorders = minimal => {
if (minimal) {
return { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
, 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
, 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
, 'right': '' , 'right-mid': '' , 'middle': ' ' }
};
return { 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗'
,'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝'
,'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼'
,'right': '║' , 'right-mid': '╢' , 'middle': '│' };
};

e.getTableStyles = minimal => {
if (minimal) {
return { 'padding-left': 0, 'padding-right': 0 };
}
};

e.getTableHeaders = (emojis, secondColumnName ) => {
const head = [
'Rank',
secondColumnName,
`Confirmed ${emojis ? ' ✅': ''}`,
`Recovered${emojis ? ' 😀' : ''}`,
`Deaths${emojis ? ' 😞' : ''}`,
`Active${emojis ? ' 😷' : ''}`,
'Mortality %',
'Recovered %',
'1 Day ▲',
'1 Week ▲',
// 'RoG',
...( emojis ? ['🏳'] : [] ),
];
return head;
};
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "coronavirus-tracker-cli",
"version": "0.4.0",
"version": "0.5.0",
"description": "track conronavirus cases from cli",
"main": "./lib/corona.js",
"bin": {
Expand Down

0 comments on commit a6e12a5

Please sign in to comment.