Skip to content

Commit

Permalink
Lint code and refactor some places
Browse files Browse the repository at this point in the history
  • Loading branch information
homerchen19 committed Jan 15, 2019
1 parent 6308de8 commit 8832cc7
Show file tree
Hide file tree
Showing 25 changed files with 247 additions and 123 deletions.
3 changes: 2 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env node

if (process.env.NODE_ENV === 'development') {
require('babel-register');
require('@babel/register');

require('../src/cli');
} else {
require('../lib/cli');
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"husky": "^1.3.1",
"jest": "^23.6.0",
"lint-staged": "^8.1.0",
"moment-timezone": "^0.5.23",
"pkg": "^4.3.7",
"prettier": "^1.15.3",
"prettier-package-json": "^2.0.1",
Expand Down
13 changes: 7 additions & 6 deletions src/__tests__/cli.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
jest.mock('update-notifier');
jest.mock('chalk');

jest.mock('../command');
jest.mock('../utils/log');
Expand All @@ -12,10 +13,13 @@ let updateNotifier;
const setup = () => {
updateNotifier = require('update-notifier');
updateNotifier.mockReturnValue({ notify: jest.fn() });

log = require('../utils/log');
log.error = jest.fn();
log.error = jest.fn(s => s);
log.bold = jest.fn(s => s);
nbaGo = require('../command').default;

nbaGo = require('../command');

require('../cli');
};

Expand All @@ -40,7 +44,7 @@ describe('cli', () => {
process.argv = ['node', 'bin/cli.js', 'QQ'];
setup();

expect(log.error).toBeCalledWith(`Unknown command: ${log.bold('QQ')}`);
expect(log.error).toBeCalledWith('Unknown command: QQ');
expect(process.exit).toBeCalledWith(1);
});

Expand Down Expand Up @@ -124,23 +128,20 @@ describe('cli', () => {

it('should call nbaGo with option -t', () => {
process.argv = ['node', 'bin/cli.js', 'game', '-t'];

setup();

expect(nbaGo.game.mock.calls[0][0].today).toBe(true);
});

it('should call nbaGo with option -T', () => {
process.argv = ['node', 'bin/cli.js', 'game', '-T'];

setup();

expect(nbaGo.game.mock.calls[0][0].tomorrow).toBe(true);
});

it('should call nbaGo with option -n', () => {
process.argv = ['node', 'bin/cli.js', 'game', '-n'];

setup();

expect(nbaGo.game.mock.calls[0][0].networks).toBe(true);
Expand Down
11 changes: 8 additions & 3 deletions src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import isAsyncSupported from 'is-async-supported';
import chalk from 'chalk';
import updateNotifier from 'update-notifier';

import nbaGo from './command';
import { player as playerCommand, game as gameCommand } from './command';
import { error, bold, nbaRed, neonGreen } from './utils/log';

import pkg from '../package.json';
Expand Down Expand Up @@ -65,7 +65,8 @@ program
if (!option.info && !option.regular && !option.playoffs) {
option.info = true;
}
nbaGo.player(name, option);

playerCommand(name, option);
});

program
Expand Down Expand Up @@ -113,7 +114,8 @@ program
) {
option.today = true;
}
nbaGo.game(option);

gameCommand(option);
});

program.on('--help', () => {
Expand Down Expand Up @@ -147,14 +149,17 @@ program.on('--help', () => {

program.command('*').action(command => {
error(`Unknown command: ${bold(command)}`);

const commandNames = program.commands
.map(c => c._name)
.filter(name => name !== '*');

const closeMatch = didYouMean(command, commandNames);

if (closeMatch) {
error(`Did you mean ${bold(closeMatch)} ?`);
}

process.exit(1);
});

Expand Down
68 changes: 44 additions & 24 deletions src/command/game/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable no-await-in-loop, no-constant-condition */

import R from 'ramda';
import moment from 'moment-timezone';
import parse from 'date-fns/parse';
import addDays from 'date-fns/add_days';
import subDays from 'date-fns/sub_days';
Expand All @@ -20,28 +19,30 @@ import boxScore from './boxScore';
import live from './live';
import getBroadcastNetworks from './network';

import getApiDate from '../../utils/getApiDate';
import NBA from '../../utils/nba';
import { error, bold } from '../../utils/log';
import { cfontsDate } from '../../utils/cfonts';
import getBlessed from '../../utils/blessed';
import catchAPIError from '../../utils/catchAPIError';

const getLosAngelesTimezone = date =>
moment
.tz(date, 'America/Los_Angeles')
.startOf('day')
.format();

const getSeason = date => {
const year = R.compose(getYear, parse)(date);
const month = R.compose(getMonth, parse)(date);
const year = R.compose(
getYear,
parse
)(date);
const month = R.compose(
getMonth,
parse
)(date);

if (year < 2012 || (year === 2012 && month < 5)) {
error(
`Sorry, https://stats.nba.com/ doesn't provide season data before 2012-13 ${emoji.get(
'confused'
)}`
);

process.exit(1);
}

Expand Down Expand Up @@ -69,13 +70,18 @@ const getGameWithOptionalFilter = async (games, option) => {
) !== -1
);

if (!potentialGames.length)
console.log({ potentialGames });

if (!potentialGames.length) {
error(`Can't find any teams that match ${team}`);
else if (potentialGames.length === 1) {
} else if (potentialGames.length === 1) {
const homeTeam = await getTeamInfo(potentialGames[0].home);
const visitorTeam = await getTeamInfo(potentialGames[0].visitor);

return { game: { gameData: potentialGames[0], homeTeam, visitorTeam } };
} else return chooseGameFromSchedule(potentialGames);
} else {
return chooseGameFromSchedule(potentialGames);
}
}

return chooseGameFromSchedule(games, option);
Expand All @@ -88,7 +94,12 @@ const game = async option => {
let seasonMetaData;

if (option.date) {
if (R.compose(isValid, parse)(option.date)) {
if (
R.compose(
isValid,
parse
)(option.date)
) {
_date = format(option.date, 'YYYY-MM-DD');
} else {
error('Date is invalid');
Expand All @@ -104,33 +115,42 @@ const game = async option => {
error(`Can't find any option ${emoji.get('confused')}`);
process.exit(1);
}
R.compose(cfontsDate, getSeason)(_date);

const LADate = getLosAngelesTimezone(_date);
R.compose(
cfontsDate,
getSeason
)(_date);

const apiDate = getApiDate(_date);

try {
const {
sports_content: { games: { game: _gamesData } },
} = await NBA.getGamesFromDate(LADate);
sports_content: {
games: { game: _gamesData },
},
} = await NBA.getGames(apiDate);

gamesData = _gamesData;
} catch (err) {
catchAPIError(err, 'NBA.getGamesFromDate()');
catchAPIError(err, 'NBA.getGames()');
}

const {
game: { homeTeam, visitorTeam, gameData },
} = await getGameWithOptionalFilter(gamesData, option);

try {
const {
sports_content: {
game: _gameBoxScoreData,
sports_meta: { season_meta: _seasonMetaData },
},
} = await NBA.getBoxScoreFromDate(LADate, gameData.id);
} = await NBA.getBoxScore({ ...apiDate, gameId: gameData.id });

gameBoxScoreData = _gameBoxScoreData;
seasonMetaData = _seasonMetaData;
} catch (err) {
catchAPIError(err, 'NBA.getBoxScoreFromDate()');
catchAPIError(err, 'NBA.getBoxScore()');
}

const { home, visitor } = gameBoxScoreData;
Expand Down Expand Up @@ -227,21 +247,21 @@ const game = async option => {
try {
const {
sports_content: { game: _updatedPlayByPlayData },
} = await NBA.getPlayByPlayFromDate(LADate, gameData.id);
} = await NBA.getPlayByPlay({ ...apiDate, gameId: gameData.id });

updatedPlayByPlayData = _updatedPlayByPlayData;
} catch (err) {
catchAPIError(err, 'NBA.getPlayByPlayFromDate()');
catchAPIError(err, 'NBA.getPlayByPlay()');
}

try {
const {
sports_content: { game: _updatedGameBoxScoreData },
} = await NBA.getBoxScoreFromDate(LADate, gameData.id);
} = await NBA.getBoxScore({ ...apiDate, gameId: gameData.id });

updatedGameBoxScoreData = _updatedGameBoxScoreData;
} catch (err) {
catchAPIError(err, 'NBA.getBoxScoreFromDate()');
catchAPIError(err, 'NBA.getBoxScore()');
}

gamePlayByPlayData = updatedPlayByPlayData;
Expand Down
8 changes: 6 additions & 2 deletions src/command/game/live.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,12 @@ const live = (
} = blessedComponents;

const {
home: { linescores: { period: homeTeamPeriod } },
visitor: { linescores: { period: visitorTeamPeriod } },
home: {
linescores: { period: homeTeamPeriod },
},
visitor: {
linescores: { period: visitorTeamPeriod },
},
} = gameBoxScoreData;

updateTeamQuarterScores(homeTeam, latestPeriod, homeTeamPeriod);
Expand Down
44 changes: 29 additions & 15 deletions src/command/game/schedule.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Team from '../Team';

import NBA from '../../utils/nba';
import { bold, neonGreen } from '../../utils/log';
import catchAPIError from '../../utils/catchAPIError';

const MAX_WIDTH = 81;
const TEAMNAME_WIDTH = 20;
Expand Down Expand Up @@ -45,9 +46,10 @@ const createGameChoice = (homeTeam, visitorTeam, periodTime, broadcasters) => {
? visitorTeam.getWinnerName('right')
: visitorTeam.getName({ color: true })
);
const match = `${homeTeamName}${center(emoji.get('basketball'), 8)}${
visitorTeamName
}`;
const match = `${homeTeamName}${center(
emoji.get('basketball'),
8
)}${visitorTeamName}`;
const homeTeamScore =
winner === 'home'
? right(bold(neonGreen(homeTeam.getScore())), 4)
Expand All @@ -73,27 +75,35 @@ const createGameChoice = (homeTeam, visitorTeam, periodTime, broadcasters) => {
};

const getTeamInfo = async (team, seasonId) => {
const { teamInfoCommon: teamInfo } = await NBA.teamInfoCommon({
TeamID: team.id,
Season: seasonId,
});

return new Team({
...teamInfo[0],
score: team.score,
linescores: team.linescores,
isHomeTeam: true,
});
try {
const { teamInfoCommon: teamInfo } = await NBA.teamInfoCommon({
TeamID: team.id,
Season: seasonId,
});

return new Team({
...teamInfo[0],
score: team.score,
linescores: team.linescores,
isHomeTeam: true,
});
} catch (err) {
catchAPIError(err, 'NBA.teamInfoCommon()');
}
};

const chooseGameFromSchedule = async (gamesData, option) => {
const spinner = ora('Loading Game Schedule').start();
const spinner = ora(
`Loading Game Schedule...(0/${gamesData.length})`
).start();
let networksHeader = '';

if (option.networks) {
networksHeader = `${padHomeTeamNetwork('Home')} ${emoji.get(
'tv'
)} ${padAwayTeamNetwork('Away')}|`;
}

const header = `│ ${padHomeTeamName('Home')}${center(
emoji.get('basketball'),
8
Expand Down Expand Up @@ -125,6 +135,10 @@ const chooseGameFromSchedule = async (gamesData, option) => {
const homeTeam = await getTeamInfo(home, process.env.season);
const visitorTeam = await getTeamInfo(visitor, process.env.season);

spinner.text = `Loading Game Schedule...(${index + 1}/${
gamesData.length
})`;

questions[0].choices.push({
name: createGameChoice(
homeTeam,
Expand Down
7 changes: 4 additions & 3 deletions src/command/game/scoreboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,10 @@ const scoreboard = (
{
colSpan: 6,
content: bold(
`${emoji.get('calendar')} ${format(date, 'YYYY/MM/DD')} ${
formatedTime
}`
`${emoji.get('calendar')} ${format(
date,
'YYYY/MM/DD'
)} ${formatedTime}`
),
hAlign: 'center',
},
Expand Down
6 changes: 2 additions & 4 deletions src/command/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
import player from './player';
import game from './game';

export default { player, game };
export { default as player } from './player';
export { default as game } from './game';
Loading

0 comments on commit 8832cc7

Please sign in to comment.