Skip to content

Commit

Permalink
Removed XML and CSV support. Save results in local folder.
Browse files Browse the repository at this point in the history
  • Loading branch information
bradbarkhouse committed Jun 22, 2017
1 parent c96377c commit 2df6330
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 292 deletions.
142 changes: 67 additions & 75 deletions lib/API_v1_0.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var Q = require('q');
var rp = require('request-promise');
var fs = require('fs');
var util = require('util');
var xml2json = require('./xml2json.js');
var libVersion = require('../package.json').version;

// Private Vars
var platform = util.format('%s-%s%s', os.arch(), os.platform(), os.release());
Expand All @@ -12,12 +12,17 @@ var options = {
uri: '',
json: true,
resolveWithFullResponse: true,
gzip: true,
headers: {
'Authorization': '',
'Accept-Encoding': 'gzip',
'User-Agent': util.format('MySportsFeeds-Node/%s (%s)', libVersion, platform)
},
qs: {}
qs: {},
transform: function(body) {
// console.log("response = '" + util.inspect(body, {depth: null}) + "'");

return body;
}
};
var auth = null;
var baseUrl = "https://www.mysportsfeeds.com/api/feed/pull";
Expand All @@ -40,9 +45,10 @@ function __verifyFeedName(feed) {
}

function __verifyFormat(format) {
var isValid = false;
var isValid = true;

if ( format != 'json' && format != 'xml' && format != 'csv' ) {
// Only JSON format supported
if ( format != 'json' ) {
isValid = false;
}

Expand All @@ -60,7 +66,7 @@ function __leagueAndSeasonUrl(league, season, feed, format, params) {
function __makeOutputFilename(league, season, feed, format, params) {
var filename = feed + '-' + league + '-' + season;

if (Object.keys(params).includes("gameid") ) {
if ( Object.keys(params).includes("gameid") ) {
filename += "-" + params["gameid"];
}

Expand All @@ -73,65 +79,39 @@ function __makeOutputFilename(league, season, feed, format, params) {
return filename;
}

function __parseXml(xmlStr) {
var dom = null;

if ( window.DOMParser ) {
try {
dom = (new DOMParser()).parseFromString(xmlStr, "text/xml");
} catch (e) {
dom = null;
}
} else if ( window.ActiveXObject ) {
try {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;

if ( !dom.loadXML(xml) ) { // parse error ..
throw new Error(dom.parseError.reason + dom.parseError.srcText);
}
} catch (e) {
dom = null;
}
} else {
throw new Error("cannot parse xml string!");
}

return dom;
}

function __saveFeed(response, league, season, feed, format, params) {
var storeOutput = null;
var filename = "";

// Save to memory regardless of selected method
if ( format == "json" ) {
storeOutput = JSON.parse(response);
storeOutput = response;
} else if ( format == "xml" ) {
storeOutput = eval(xml2json(__parseXml(response)));
throw new Error("XML feed format not supported in this version.");
} else if ( format == "csv" ) {
throw new Error("CSV feed format not supported.");
throw new Error("CSV feed format not supported in this version.");
}

if ( storeType == "file" ) {
if ( !fs.existsSync(storeLocation) ) {
fs.mkdir(storeLocation);
}

filename = __makeOutputFilename(league, season, feed, format, params);
var filename = __makeOutputFilename(league, season, feed, format, params);

if ( format == "json" ) { // This is JSON
fs.writeFileSync(filename, JSON.stringify(storeOutput));
} else if ( format == "xml" ) { // This is xml
fs.writeFileSync(filename, JSON.stringify(storeOutput));
fs.writeFileSync(storeLocation + filename, JSON.stringify(storeOutput));
} else {
throw new Error("Could not interpret feed output format.");
}

if ( verbose ) {
console.log("File saved as '" + storeLocation + filename + "'.");
}
}
}

// Public Functions
function API_v1_0(v, storeT, storeL) {
var API_v1_0 = function(v, storeT, storeL) {
verbose = v;
storeType = storeT;
storeLocation = storeL;
Expand All @@ -152,9 +132,13 @@ function API_v1_0(v, storeT, storeL) {
'active_players',
'player_injuries',
'latest_updates',
'daily_dfs'
'daily_dfs',
'overall_team_standings',
'division_team_standings',
'conference_team_standings',
'playoff_team_standings'
];
}
};

// Indicate this version does support BASIC auth
API_v1_0.prototype.supportsBasicAuth = function() {
Expand All @@ -177,28 +161,29 @@ API_v1_0.prototype.getData = function(league, season, feed, format, params) {
throw new Error("You must authenticate() before making requests.");
}

// add force=false parameter (helps prevent unnecessary bandwidth use)
// Add force=false parameter (helps prevent unnecessary bandwidth use)
if ( !Object.keys(params).includes("force") ) {
params['force'] = 'false';
}

if ( !__verifyFeedName(feed) ) {
throw new Error("Unknown feed '" + feed + "'.");
}

if ( !__verifyFormat(format) ) {
throw new Error("Unsupported format '" + output_format + "'.");
throw new Error("Unsupported format '" + format + "'.");
}

var url = "";

if ( feed == 'current_season' ) {
url = __leagueOnlyUrl(league, feed, output_format, params);
url = __leagueOnlyUrl(league, feed, format, params);
} else {
url = __leagueAndSeasonUrl(league, season, feed, output_format, params);
url = __leagueAndSeasonUrl(league, season, feed, format, params);
}

if ( verbose ) {
console.log("Making API request to '" + url + "'.";
console.log("Making API request to '" + url + "'.");
console.log(" with headers:");
console.log(options.headers);
console.log(" and params:");
Expand All @@ -210,45 +195,52 @@ API_v1_0.prototype.getData = function(league, season, feed, format, params) {
options.qs = params;

// Make the request
rp(options).then(function(response) {
var data = response.body;
rp(options).then(function(body) {
var data = body;

if ( storeType ) {
__saveFeed(data, league, season, feed, format, params);
}

if ( format == "json" ) {
data = body;
} else if ( format == "xml" ) {
throw new Error("XML feed format not supported in this version.");
} else if ( format == "csv" ) {
throw new Error("CSV feed format not supported in this version.");
}

if ( response.statusCode == 200 ) { // Success!
if ( storeType ) {
__saveFeed(data, league, season, feed, format, params);
deferred.resolve(data);
})
.catch(function(err) {
if ( verbose ) {
console.log("err = '" + util.inspect(err, {depth: null}) + "'");
}

if ( err.statusCode == 304 ) { // Content hasn't changed, read from local file
if ( verbose ) {
console.log("Data hasn't changed since last call.");
}

var filename = __makeOutputFilename(league, season, feed, format, params);

var data = fs.readFileSync(storeLocation + filename);

if ( format == "json" ) {
data = JSON.parse(data);
} else if ( format == "xml" ) {
data = eval(xml2json(__parseXml(data)));
throw new Error("XML feed format not supported in this version.");
} else if ( format == "csv" ) {
throw new Error("CSV feed format not supported.");
}
} else if ( response.statusCode == 304 ) { // Content hasn't changed, read from local file
if ( verbose ) {
console.log("Data hasn't changed since last call.");
throw new Error("CSV feed format not supported in this version.");
}

var filename = __makeOutputFilename(league, season, feed, output_format, params);

fs.readFile(storeLocation + filename, function(err, data) {
if ( format == "json" ) {
data = JSON.parse(data);
} else if ( format == "xml" ) {
data = eval(xml2json(__parseXml(data)));
} else if ( format == "csv" ) {
throw new Error("CSV feed format not supported.");
}
});
deferred.resolve(data);
} else {
throw new Error("API call failed with error: " + response.statusCode);
throw new Error("API call failed with error: " + err.statusCode);
}

deferred.resolve(data);
});

return deferred.promise;
};

module.exports = API_v1_0;
exports = module.exports = API_v1_0;
57 changes: 0 additions & 57 deletions lib/MySportsFeeds.js

This file was deleted.

58 changes: 56 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,57 @@
var msf = require('./MySportsFeeds.js');
var API_v1_0 = require('./api_v1_0.js');

exports.MySportsFeeds = msf.MySportsFeeds;
// Private Vars
var apiVersion = "1.0";
var storeType = "file";
var storeLocation = "results/";
var apiInstance = null;

// Private Functions
function __verifyVersion(version) {
if ( version != '1.0' ) {
throw new Error("Unrecognized version specified. Supported versions are: '1.0'");
}
}

function __verifyStore(storeType, storeLocation) {
if ( storeType && storeType != 'file' ) {
throw new Error("Unrecognized storage type specified. Supported values are: None,'file'");
}

if ( storeType && storeType == 'file' ) {
if ( !storeLocation ) {
throw newError("Must specify a location for stored data.");
}
}
}

// Public Functions
var MySportsFeeds = function(apiVers = "1.0", verb = true, storeT = "file", storeL = "results/") {
__verifyVersion(apiVers);
__verifyStore(storeT, storeL);

apiVersion = apiVers;
verbose = verb;
storeType = storeT;
storeLocation = storeL;

// Instantiate an instance of the appropriate API depending on version
if ( apiVersion == '1.0' ) {
apiInstance = new API_v1_0(verbose, storeType,
storeLocation);
}
};

MySportsFeeds.prototype.authenticate = function(username, password) {
if ( !apiInstance.supportsBasicAuth() ) {
throw new Error("BASIC authentication not supported for version " + apiVersion);
}

apiInstance.setAuthCredentials(username, password);
};

MySportsFeeds.prototype.getData = function(league, season, feed, format, params) {
return apiInstance.getData(league, season, feed, format, params);
};

exports = module.exports = MySportsFeeds;
Loading

0 comments on commit 2df6330

Please sign in to comment.