Added linters and fixed linter warnings

This commit is contained in:
2018-04-28 23:19:02 -05:00
parent afcf9adc25
commit 8bc16155f3
5 changed files with 305 additions and 272 deletions

13
.eslintrc.json Normal file
View File

@ -0,0 +1,13 @@
{
"extends": "strongloop",
"rules": {
"max-len": [2, 120, 8]
},
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"mocha": true,
"es6": true
}
}

View File

@ -1,11 +1,13 @@
const ShiftStats = require('./index') 'use strict';
let s = new ShiftStats() const ShiftStats = require('./index');
let s = new ShiftStats();
// with promises // with promises
s.login().then(() => { s.login().then(() => {
return s.divisionStandings(4702) return s.divisionStandings(4702);
}).then(async (standings) => { }).then(async(standings) => {
console.log(standings.teams) console.log(standings.teams);
// with async/await // with async/await
console.log((await s.gameGoals(166658, 'home')).home_goals) console.log((await s.gameGoals(166658, 'home')).home_goals);
}) });

165
index.js
View File

@ -1,222 +1,237 @@
const http = require('http') 'use strict';
const querystring = require('querystring')
const zlib = require('zlib') const http = require('http');
const querystring = require('querystring');
const zlib = require('zlib');
class Request { class Request {
_request(options) { _request(options) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
http.get(options, (response) => { http.get(options, (response) => {
const { statusCode } = response const { statusCode } = response;
const contentType = response.headers['content-type'] const contentType = response.headers['content-type'];
let error let error;
if (statusCode !== 200) { if (statusCode !== 200) {
error = new Error(`Request Failed.\nStatus Code: ${statusCode}`) error = new Error(`Request Failed.\nStatus Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) { } else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`) error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`);
} }
if (error) { if (error) {
response.resume() response.resume();
reject(error) reject(error);
return return;
} }
let rawData = '' let rawData = '';
const gunzip = zlib.createGunzip() const gunzip = zlib.createGunzip();
gunzip.on('data', (chunk) => { gunzip.on('data', (chunk) => {
rawData += chunk rawData += chunk;
}).on('end', () => { }).on('end', () => {
try { try {
const parsedData = JSON.parse(rawData) const parsedData = JSON.parse(rawData);
resolve(parsedData) resolve(parsedData);
} catch (e) { } catch (e) {
reject(e) reject(e);
} }
}) });
response.pipe(gunzip) response.pipe(gunzip);
}).on('error', (e) => { }).on('error', (e) => {
reject(e) reject(e);
}) });
}) });
} }
} }
module.exports = class ShiftStats extends Request { module.exports = class ShiftStats extends Request {
constructor(apiKey) { constructor(apiKey) {
super() super();
this.apiKey = apiKey || 'YXBpLnNoaWZ0c3RhdHMuY29tLDE5YjhhZGIwNDVjZjAxMzJhM2E5N2VmZDQ1YTRj' this.apiKey = apiKey || 'YXBpLnNoaWZ0c3RhdHMuY29tLDE5YjhhZGIwNDVjZjAxMzJhM2E5N2VmZDQ1YTRj';
} }
_request(options) { _request(options) {
return super._request({ return super._request({
hostname: 'api.shiftstats.com', hostname: 'api.shiftstats.com',
path: this._url(options.url, options.query), path: this._url(options.url, options.query),
headers: options.headers || this._headers() headers: options.headers || this._headers(),
}) });
} }
_basicHeaders() { _basicHeaders() {
return { return {
'Accept': 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Requested-With': 'com.digitalshift.hockeyshift', 'X-Requested-With': 'com.digitalshift.hockeyshift',
'Accept-Language': 'en-US', 'Accept-Language': 'en-US',
'Accept-Encoding': 'gzip,deflate', 'Accept-Encoding': 'gzip,deflate',
'Connection': 'keep-alive', Connection: 'keep-alive',
} };
} }
_headers() { _headers() {
if (typeof this.headersWithTicket === 'undefined') { if (typeof this.headersWithTicket === 'undefined') {
this.headersWithTicket = Object.assign({'Authorization': `StatsAuth ticket="${this.ticketHash}"`}, this._basicHeaders()) this.headersWithTicket = Object.assign({
Authorization: `StatsAuth ticket="${this.ticketHash}"`,
}, this._basicHeaders());
} }
return this.headersWithTicket return this.headersWithTicket;
} }
_url(path, query) { _url(path, query) {
return `/${path}?${querystring.stringify(query)}` return `/${path}?${querystring.stringify(query)}`;
} }
_gameSubpath(gameId, path, only) { _gameSubpath(gameId, path, only) {
if (only == 'home') { if (only === 'home') {
path = `home_${path}` path = `home_${path}`;
} else if (only == 'away') { } else if (only === 'away') {
path = `away_${path}` path = `away_${path}`;
} }
return this._request({ url: `game/${gameId}/${path}` }) return this._request({ url: `game/${gameId}/${path}` });
} }
login() { login() {
return this._request({ url: 'login', query: {key: this.apiKey}, headers: this._basicHeaders() }).then((json) => { return this._request({ url: 'login', query: {key: this.apiKey}, headers: this._basicHeaders() }).then((json) => {
this.ticketHash = json.ticket.hash this.ticketHash = json.ticket.hash;
return json return json;
}) });
} }
leagues() { leagues() {
return this._request({ url: 'leagues' }) return this._request({ url: 'leagues' });
} }
league(leagueId) { league(leagueId) {
return this._request({ url: `league/${leagueId}` }) return this._request({ url: `league/${leagueId}` });
} }
leagueSeasons(leagueId) { leagueSeasons(leagueId) {
return this._request({ url: `league/${leagueId}/seasons` }) return this._request({ url: `league/${leagueId}/seasons` });
} }
leagueSuspensions(leagueId, onlyActive = true) { leagueSuspensions(leagueId, onlyActive = true) {
let query = {} let query = {};
if (onlyActive) { if (onlyActive) {
query.status = 'active' query.status = 'active';
} }
return this._request({ url: `league/${leagueId}/suspensions`, query: query }) return this._request({ url: `league/${leagueId}/suspensions`, query: query });
} }
teamSearch(sport, name) { teamSearch(sport, name) {
return this._request({ url: 'teams', query: {name: name, not_ended: true, sport: sport.toLowerCase()} }) return this._request({ url: 'teams', query: {name: name, not_ended: true, sport: sport.toLowerCase()} });
} }
teamSchedule(teamId) { teamSchedule(teamId) {
return this._request({ url: `team/${teamId}/games`, query: {future: true, today: true, past: true} }) return this._request({ url: `team/${teamId}/games`, query: {future: true, today: true, past: true} });
} }
teamPlayersList(teamId) { teamPlayersList(teamId) {
return this._request({ url: `team/${teamId}/players`, query: {status: 'active'} }) return this._request({ url: `team/${teamId}/players`, query: {status: 'active'} });
} }
teamsInDivision(divisionName, leagueId, currentSeason = true) { teamsInDivision(divisionName, leagueId, currentSeason = true) {
return this._request({ url: 'teams', query: {division: divisionName, league_id: leagueId, not_ended: currentSeason} }) return this._request({ url: 'teams', query: {
division: divisionName,
league_id: leagueId,
not_ended: currentSeason,
} });
} }
teamGames(teamId, includeFuture = true, includeToday = true) { teamGames(teamId, includeFuture = true, includeToday = true) {
return this._request({ url: `team/${teamId}/games`, query: {future: includeFuture, today: includeToday} }) return this._request({ url: `team/${teamId}/games`, query: {future: includeFuture, today: includeToday} });
} }
teamGamesForStatus(teamId, status = 'Final,In Progress,Forfeit') { teamGamesForStatus(teamId, status = 'Final,In Progress,Forfeit') {
return this._request({ url: `team/${teamId}/games`, query: {status: status} }) return this._request({ url: `team/${teamId}/games`, query: {status: status} });
} }
teamPractices(teamId, includeFuture = true, includeToday = true) { teamPractices(teamId, includeFuture = true, includeToday = true) {
return this._request({ url: `team/${teamId}/practices`, query: {future: includeFuture, today: includeToday} }) return this._request({ url: `team/${teamId}/practices`, query: {future: includeFuture, today: includeToday} });
} }
teamSuspensions(teamId, onlyActive = true) { teamSuspensions(teamId, onlyActive = true) {
let query = {} let query = {};
if (onlyActive) { if (onlyActive) {
query.status = 'active' query.status = 'active';
} }
return this._request({ url: `team/${teamId}/suspensions`, query: query }) return this._request({ url: `team/${teamId}/suspensions`, query: query });
} }
game(gameId) { game(gameId) {
return this._request({ url: `game/${gameId}` }) return this._request({ url: `game/${gameId}` });
} }
// only is 'home' or 'away', optional // only is 'home' or 'away', optional
gameGoals(gameId, only = null) { gameGoals(gameId, only = null) {
return this._gameSubpath(gameId, 'goals', only) return this._gameSubpath(gameId, 'goals', only);
} }
// only is 'home' or 'away', optional // only is 'home' or 'away', optional
gameGoalies(gameId, only = null) { gameGoalies(gameId, only = null) {
return this._gameSubpath(gameId, 'goalies', only) return this._gameSubpath(gameId, 'goalies', only);
} }
// only is 'home' or 'away', optional // only is 'home' or 'away', optional
gamePenalties(gameId, only = null) { gamePenalties(gameId, only = null) {
return this._gameSubpath(gameId, 'penalties', only) return this._gameSubpath(gameId, 'penalties', only);
} }
// only is 'home' or 'away', optional // only is 'home' or 'away', optional
gameRoster(gameId, only = null) { gameRoster(gameId, only = null) {
return this._gameSubpath(gameId, 'roster', only) return this._gameSubpath(gameId, 'roster', only);
} }
divisionGamesList(divisionId) { divisionGamesList(divisionId) {
return this._request({ url: `division/${divisionId}/games` }) return this._request({ url: `division/${divisionId}/games` });
} }
// type is 'Regular Season', 'Playoffs', or 'Exhibition', required // type is 'Regular Season', 'Playoffs', or 'Exhibition', required
divisionStandings(divisionId, type = 'Regular Season') { divisionStandings(divisionId, type = 'Regular Season') {
return this._request({ url: `division/${divisionId}/standings`, query: {type: type} }) return this._request({ url: `division/${divisionId}/standings`, query: {type: type} });
} }
divisionTeams(divisionId) { divisionTeams(divisionId) {
return this._request({ url: `division/${divisionId}/teams` }) return this._request({ url: `division/${divisionId}/teams` });
} }
// type is 'Regular Season', 'Playoffs', or 'Exhibition', required // type is 'Regular Season', 'Playoffs', or 'Exhibition', required
// limit, required // limit, required
// metrics, required // metrics, required
divisionLeaders(divisionId, type = 'Regular Season', limit = 20, metrics = ['points', 'goals', 'assists', 'goals_against_average', 'save_percentage', 'wins', 'shutouts', 'number_first_stars', 'number_stars']) { divisionLeaders(divisionId, type = 'Regular Season', limit = 20, metrics = [
return this._request({ url: `division/${divisionId}/leaders`, query: {limit: limit, metrics: metrics.join(','), type: type} }) 'points', 'goals', 'assists', 'goals_against_average', 'save_percentage',
'wins', 'shutouts', 'number_first_stars', 'number_stars',
]) {
return this._request({ url: `division/${divisionId}/leaders`, query: {
limit: limit,
metrics: metrics.join(','),
type: type,
} });
} }
divisionSuspensions(divisionId, onlyActive = true) { divisionSuspensions(divisionId, onlyActive = true) {
let query = {} let query = {};
if (onlyActive) { if (onlyActive) {
query.status = 'active' query.status = 'active';
} }
return this._request({ url: `division/${divisionId}/suspensions`, query: query }) return this._request({ url: `division/${divisionId}/suspensions`, query: query });
} }
season(seasonId) { season(seasonId) {
return this._request({ url: `season/${seasonId}` }) return this._request({ url: `season/${seasonId}` });
} }
seasonDivisionsList(seasonId) { seasonDivisionsList(seasonId) {
return this._request({ url: `season/${seasonId}/divisions` }) return this._request({ url: `season/${seasonId}/divisions` });
} }
seasonSuspensions(seasonId, onlyActive = true) { seasonSuspensions(seasonId, onlyActive = true) {
let query = {} let query = {};
if (onlyActive) { if (onlyActive) {
query.status = 'active' query.status = 'active';
} }
return this._request({ url: `season/${seasonId}/suspensions`, query: query }) return this._request({ url: `season/${seasonId}/suspensions`, query: query });
} }
} };

View File

@ -25,9 +25,12 @@
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "chai": "^4.1.2",
"chai-as-promised-compat": "^7.0.3", "chai-as-promised-compat": "^7.0.3",
"eslint": "^4.19.1",
"eslint-config-strongloop": "^2.1.0",
"mocha": "^5.1.1" "mocha": "^5.1.1"
}, },
"scripts": { "scripts": {
"test": "mocha test/*.spec.js" "test": "mocha test/*.spec.js",
"pretest": "eslint --ignore-path .gitignore ."
} }
} }

View File

@ -1,297 +1,297 @@
'use strict' 'use strict';
const ShiftStats = require('../index') const ShiftStats = require('../index');
const chai = require('chai') const chai = require('chai');
let expect = chai.expect let expect = chai.expect;
const chaiAsPromised = require("chai-as-promised-compat") const chaiAsPromised = require('chai-as-promised-compat');
chai.use(chaiAsPromised) chai.use(chaiAsPromised);
describe('ShiftStats', () => { describe('ShiftStats', () => {
describe('bad api key', () => { describe('bad api key', () => {
it('throws an error', () => { it('throws an error', () => {
let s = new ShiftStats('a') let s = new ShiftStats('a');
expect(s.login()).to.be.rejected expect(s.login()).to.be.rejected;
}) });
}) });
describe('with valid api key', function() { describe('with valid api key', function() {
this.timeout(0) this.timeout(0);
let s = new ShiftStats() let s = new ShiftStats();
before(async () => { before(async() => {
await s.login() await s.login();
}) });
context('teamSearch', () => { context('teamSearch', () => {
let teamSearch let teamSearch;
before(async () => { before(async() => {
teamSearch = await s.teamSearch('hockey', 'bears') teamSearch = await s.teamSearch('hockey', 'bears');
}) });
it('returns some teams', () => { it('returns some teams', () => {
expect(teamSearch).to.have.property('teams') expect(teamSearch).to.have.property('teams');
expect(teamSearch.teams).to.be.an('array') expect(teamSearch.teams).to.be.an('array');
}) });
it('finds the right team', () => { it('finds the right team', () => {
let bears = teamSearch.teams.find(team => team.id == 18827) let bears = teamSearch.teams.find(team => team.id === 18827);
expect(bears).to.have.property('id') expect(bears).to.have.property('id');
}) });
}) });
context('teamSchedule', () => { context('teamSchedule', () => {
let teamSchedule let teamSchedule;
before(async () => { before(async() => {
teamSchedule = await s.teamSchedule(18827) teamSchedule = await s.teamSchedule(18827);
}) });
it('returns a schedule', () => { it('returns a schedule', () => {
expect(teamSchedule).to.have.property('games') expect(teamSchedule).to.have.property('games');
}) });
}) });
context('teamPlayersList', () => { context('teamPlayersList', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamPlayersList(18827) ret = await s.teamPlayersList(18827);
}) });
it('returns players', () => { it('returns players', () => {
expect(ret).to.have.property('players') expect(ret).to.have.property('players');
}) });
}) });
context('divisionGamesList', () => { context('divisionGamesList', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.divisionGamesList(3057) ret = await s.divisionGamesList(3057);
}) });
it('returns a list of games', () => { it('returns a list of games', () => {
expect(ret).to.have.property('games') expect(ret).to.have.property('games');
}) });
}) });
context('seasonDivisionsList', () => { context('seasonDivisionsList', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.seasonDivisionsList(741) ret = await s.seasonDivisionsList(741);
}) });
it('returns a list of divisions', () => { it('returns a list of divisions', () => {
expect(ret).to.have.property('divisions') expect(ret).to.have.property('divisions');
}) });
}) });
context('seasonSuspensions', () => { context('seasonSuspensions', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.seasonSuspensions(741, false) ret = await s.seasonSuspensions(741, false);
}) });
it('returns a list of suspensions', () => { it('returns a list of suspensions', () => {
expect(ret).to.have.property('suspensions') expect(ret).to.have.property('suspensions');
}) });
}) });
context('leagues', () => { context('leagues', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.leagues() ret = await s.leagues();
}) });
it('returns a list of leagues', () => { it('returns a list of leagues', () => {
expect(ret).to.have.property('leagues') expect(ret).to.have.property('leagues');
}) });
}) });
context('league', () => { context('league', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.league(3) ret = await s.league(3);
}) });
it('returns a league', () => { it('returns a league', () => {
expect(ret).to.have.property('league') expect(ret).to.have.property('league');
}) });
}) });
context('leagueSeasons', () => { context('leagueSeasons', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.leagueSeasons(3) ret = await s.leagueSeasons(3);
}) });
it('returns a list of seasons', () => { it('returns a list of seasons', () => {
expect(ret).to.have.property('seasons') expect(ret).to.have.property('seasons');
}) });
}) });
context('leagueSeasons', () => { context('leagueSeasons', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.leagueSuspensions(3, true) ret = await s.leagueSuspensions(3, true);
}) });
it('returns a list of suspensions', () => { it('returns a list of suspensions', () => {
expect(ret).to.have.property('suspensions') expect(ret).to.have.property('suspensions');
}) });
}) });
context('teamsInDivision', () => { context('teamsInDivision', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamsInDivision('XPL', 317, true) ret = await s.teamsInDivision('XPL', 317, true);
}) });
it('returns a list of teams', () => { it('returns a list of teams', () => {
expect(ret).to.have.property('teams') expect(ret).to.have.property('teams');
}) });
}) });
context('teamGames', () => { context('teamGames', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamGames(1, true, true) ret = await s.teamGames(1, true, true);
}) });
it('returns a list of games', () => { it('returns a list of games', () => {
expect(ret).to.have.property('games') expect(ret).to.have.property('games');
}) });
}) });
context('teamGamesForStatus', () => { context('teamGamesForStatus', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamGamesForStatus(1, 'Final,In Progress') ret = await s.teamGamesForStatus(1, 'Final,In Progress');
}) });
it('returns a list of games', () => { it('returns a list of games', () => {
expect(ret).to.have.property('games') expect(ret).to.have.property('games');
}) });
}) });
context('teamPractices', () => { context('teamPractices', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamPractices(18827, true, true) ret = await s.teamPractices(18827, true, true);
}) });
it('returns a list of practices', () => { it('returns a list of practices', () => {
expect(ret).to.have.property('practices') expect(ret).to.have.property('practices');
}) });
}) });
context('teamSuspensions', () => { context('teamSuspensions', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.teamSuspensions(18827, false) ret = await s.teamSuspensions(18827, false);
}) });
it('returns a list of suspensions', () => { it('returns a list of suspensions', () => {
expect(ret).to.have.property('suspensions') expect(ret).to.have.property('suspensions');
}) });
}) });
context('game', () => { context('game', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.game(128740) ret = await s.game(128740);
}) });
it('returns game info', () => { it('returns game info', () => {
expect(ret).to.have.property('game') expect(ret).to.have.property('game');
}) });
}) });
context('gameGoals', () => { context('gameGoals', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.gameGoals(128740, 'away') ret = await s.gameGoals(128740, 'away');
}) });
it('returns a list of away goals', () => { it('returns a list of away goals', () => {
expect(ret).to.have.property('away_goals') expect(ret).to.have.property('away_goals');
}) });
}) });
context('gameGoalies', () => { context('gameGoalies', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.gameGoalies(128740, 'away') ret = await s.gameGoalies(128740, 'away');
}) });
it('returns a list of away goalies', () => { it('returns a list of away goalies', () => {
expect(ret).to.have.property('away_goalies') expect(ret).to.have.property('away_goalies');
}) });
}) });
context('gamePenalties', () => { context('gamePenalties', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.gamePenalties(128740, 'away') ret = await s.gamePenalties(128740, 'away');
}) });
it('returns a list of away penalties', () => { it('returns a list of away penalties', () => {
expect(ret).to.have.property('away_penalties') expect(ret).to.have.property('away_penalties');
}) });
}) });
context('gameRoster', () => { context('gameRoster', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.gameRoster(128740, 'away') ret = await s.gameRoster(128740, 'away');
}) });
it('returns an away roster', () => { it('returns an away roster', () => {
expect(ret).to.have.property('away_roster') expect(ret).to.have.property('away_roster');
}) });
}) });
context('divisionStandings', () => { context('divisionStandings', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.divisionStandings(3057, 'Regular Season') ret = await s.divisionStandings(3057, 'Regular Season');
}) });
it('returns ranked list of teams', () => { it('returns ranked list of teams', () => {
expect(ret).to.have.property('teams') expect(ret).to.have.property('teams');
}) });
}) });
context('divisionTeams', () => { context('divisionTeams', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.divisionTeams(3057) ret = await s.divisionTeams(3057);
}) });
it('returns a list of teams', () => { it('returns a list of teams', () => {
expect(ret).to.have.property('teams') expect(ret).to.have.property('teams');
}) });
}) });
context('divisionLeaders', () => { context('divisionLeaders', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.divisionLeaders(3057, 'Regular Season', 5, ['points', 'goals', 'assists']) ret = await s.divisionLeaders(3057, 'Regular Season', 5, ['points', 'goals', 'assists']);
}) });
it('returns a list of leaders', () => { it('returns a list of leaders', () => {
expect(ret).to.have.property('leaders') expect(ret).to.have.property('leaders');
}) });
}) });
context('divisionSuspensions', () => { context('divisionSuspensions', () => {
let ret let ret;
before(async () => { before(async() => {
ret = await s.divisionSuspensions(3057, false) ret = await s.divisionSuspensions(3057, false);
}) });
it('returns a list of suspensions', () => { it('returns a list of suspensions', () => {
expect(ret).to.have.property('suspensions') expect(ret).to.have.property('suspensions');
}) });
}) });
}) });
}) });