Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

📦 NEW: Option --date #60

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const getStates = require('./utils/getStates.js');
const getCountry = require('./utils/getCountry.js');
const getWorldwide = require('./utils/getWorldwide.js');
const getCountries = require('./utils/getCountries.js');
const validateOptions = require('./utils/validateOptions');
const commonUtils = require('./utils/commonUtils');
const {
style,
single,
Expand All @@ -30,14 +32,22 @@ const xcolor = cli.flags.xcolor;
const sortBy = cli.flags.sort;
const reverse = cli.flags.reverse;
const limit = Math.abs(cli.flags.limit);
const date = cli.flags.date;
const minimal = cli.flags.minimal;
const options = { sortBy, limit, reverse, minimal };

const options = { sortBy, limit, reverse, date, minimal };
const flagValidation = validateOptions(cli.flags);
(async () => {
// Init.
init(minimal);
const [input] = cli.input;
input === 'help' && (await cli.showHelp(0));
if (flagValidation.status) {
commonUtils.throwError({
type: flagValidation.type,
message: flagValidation.error
});
await cli.showHelp(0);
}
const states = input === 'states' ? true : false;
const country = input;

Expand All @@ -48,11 +58,10 @@ const options = { sortBy, limit, reverse, minimal };
const table = !states
? new Table({ head, style, chars: border })
: new Table({ head: headStates, style, chars: border });

// Display data.
spinner.start();
const lastUpdated = await getWorldwide(table, states);
await getCountry(spinner, table, states, country);
await getCountry(spinner, table, states, country, options);
await getStates(spinner, table, states, options);
await getCountries(spinner, table, states, country, options);

Expand Down
9 changes: 9 additions & 0 deletions utils/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module.exports = meow(
${yellow(`--sort`)}, ${yellow(`-s`)} Sort data by type
${yellow(`--reverse`)}, ${yellow(`-r`)} Reverse print order
${yellow(`--limit`)}, ${yellow(`-l`)} Print only N entries
${yellow(`--date`)}, ${yellow(`-d`)} Print report for particular date

Examples
${green(`corona`)} ${cyan(`china`)}
Expand Down Expand Up @@ -54,6 +55,14 @@ module.exports = meow(
default: Number.MAX_SAFE_INTEGER,
alias: 'l'
},
date: {
type: 'string',
default: new Date()
.toISOString()
.slice(0, 10)
.replace(/-/g, ''),
alias: 'd'
},
minimal: {
type: 'boolean',
default: false,
Expand Down
71 changes: 71 additions & 0 deletions utils/commonUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const axios = require('axios');
const chalk = require('chalk');
const sym = require('log-symbols');
const handleError = require('cli-handle-error');

const dim = chalk.dim;
const red = chalk.red;
const DATE_CHAR = 6;

let validateDateFormat = function (inputDate) {
var inputDateLength = inputDate.length;
if (inputDateLength != DATE_CHAR) {
return false;
}
for (index = 0; index < inputDateLength; index++) {
if (inputDate[index] < '0' || inputDate[index] > '9') {
return false;
}
}
return true;
};

let getNinjaDateFormat = function (inputDate) {
// convert DDMMYY to YYYY-MM-DD
var formattedDate =
'20' +
inputDate.slice(4, 6) +
'-' +
inputDate.slice(2, 4) +
'-' +
inputDate.slice(0, 2);
var newDate = new Date(formattedDate);
var year = newDate.getFullYear().toString().substr(-2);
var month = newDate.getMonth() + 1 + '';
var day = newDate.getDate();
var ninjaDate = month + '/' + day + '/' + year;
return ninjaDate;
};

let throwError = function (error) {
switch (error.type) {
case 'OPTIONS_VALIDATION':
console.log(
`${red(
`${sym.error} Options validation failed.${error.message}`
)}\n`
);
break;
default:
console.log(`${sym.error} ${dim(`Error format is wrong`)}`);
}
};

let isPastDate = function (inputDate) {
var formatInputDate = new Date(
'20' +
inputDate.slice(4, 6) +
'-' +
inputDate.slice(2, 4) +
'-' +
inputDate.slice(0, 2)
);
var today = new Date();
today.setHours(0, 0, 0, 0);
return today > formatInputDate;
};

module.exports.validateDateFormat = validateDateFormat;
module.exports.throwError = throwError;
module.exports.getNinjaDateFormat = getNinjaDateFormat;
module.exports.isPastDate = isPastDate;
48 changes: 46 additions & 2 deletions utils/getCountry.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,27 @@ const axios = require('axios');
const sym = require('log-symbols');
const comma = require('comma-number');
const red = chalk.red;
const dim = chalk.dim;
const to = require('await-to-js').default;
const handleError = require('cli-handle-error');
const commonUtils = require('./commonUtils');

module.exports = async (spinner, table, states, countryName) => {
module.exports = async (
spinner,
table,
states,
countryName,
{ sortBy, limit, reverse, date }
) => {
if (countryName && !states) {
const [err, response] = await to(
axios.get(`https://corona.lmao.ninja/countries/${countryName}`)
);
handleError(`API is down, try again later.`, err, false);
handleError(
`API endpoint GET /countries is down, try again later.`,
err,
false
);
const thisCountry = response.data;

if (response.data === 'Country not found') {
Expand All @@ -24,6 +36,38 @@ module.exports = async (spinner, table, states, countryName) => {
process.exit(0);
}

// get historical data if date option is provided
if (commonUtils.isPastDate(date)) {
const [err, historicalDataresponse] = await to(
axios.get(
`https://corona.lmao.ninja/v2/historical/${countryName}`
)
);
handleError(
`API endpoint GET /v2/historical is down, try again later.`,
err,
false
);
const thisCountryHistoricalDate = historicalDataresponse.data;
var ninjaDateFormat = commonUtils.getNinjaDateFormat(date);
table.options.head[3] = `Cases ${dim(`(${ninjaDateFormat})`)}`;
table.options.head[5] = `Deaths ${red(`(${ninjaDateFormat})`)}`;
thisCountry.todayCases =
ninjaDateFormat in
thisCountryHistoricalDate['timeline']['cases']
? thisCountryHistoricalDate['timeline']['cases'][
ninjaDateFormat
]
: '-';
thisCountry.todayDeaths =
ninjaDateFormat in
thisCountryHistoricalDate['timeline']['deaths']
? thisCountryHistoricalDate['timeline']['deaths'][
ninjaDateFormat
]
: '-';
}

table.push([
`—`,
thisCountry.country,
Expand Down
7 changes: 6 additions & 1 deletion utils/getStates.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ const to = require('await-to-js').default;
const handleError = require('cli-handle-error');
const orderBy = require('lodash.orderby');

module.exports = async (spinner, table, states, { sortBy, limit, reverse }) => {
module.exports = async (
spinner,
table,
states,
{ sortBy, limit, reverse, date }
) => {
if (states) {
const [err, response] = await to(
axios.get(`https://corona.lmao.ninja/states`)
Expand Down
17 changes: 17 additions & 0 deletions utils/validateOptions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const commonUtils = require('./commonUtils');

module.exports = function (options) {
var validationResult = {
status: false,
type: '',
error: []
};
if (!commonUtils.validateDateFormat(options.date)) {
validationResult.status = true;
(validationResult.type = 'OPTIONS_VALIDATION'),
validationResult.error.push(
'`date` option must be in format YYYYMMDD'
);
}
return validationResult;
};