Commit a8c818eb authored by Aaron Tidwell's avatar Aaron Tidwell

update to const/let and resolve formatting issues

parent 91559004
...@@ -12,15 +12,14 @@ $ npm install challonge --save ...@@ -12,15 +12,14 @@ $ npm install challonge --save
var challonge = require('challonge'); var challonge = require('challonge');
var client = challonge.createClient({ var client = challonge.createClient({
apiKey: '***yourAPIKey***' apiKey: '***yourAPIKey***'
}); });
client.tournaments.index({ client.tournaments.index({
callback: function(err, data){ callback: function(err, data){
if (err) { console.log(err); return; } if (err) { console.log(err); return; }
console.log(data); console.log(data);
} }
}); });
``` ```
...@@ -31,20 +30,20 @@ var challonge = require('challonge'); ...@@ -31,20 +30,20 @@ var challonge = require('challonge');
// create a new instance of the client // create a new instance of the client
var client = challonge.createClient({ var client = challonge.createClient({
apiKey: '***yourAPIKey***', apiKey: '***yourAPIKey***',
}); });
// create a tournament // create a tournament
client.tournaments.create({ client.tournaments.create({
tournament: { tournament: {
name: 'new_tournament_name', name: 'new_tournament_name',
url: 'new_tournament_url', url: 'new_tournament_url',
tournamentType: 'single elimination', tournamentType: 'single elimination',
}, },
callback: function(err, data){ callback: function(err, data){
if (err) { console.log(err); return; } if (err) { console.log(err); return; }
console.log(data); console.log(data);
} }
}); });
``` ```
......
'use strict'; const qs = require('querystring');
const https = require('https');
var qs = require('querystring'); const errorHandler = require('./error-handler');
var https = require('https');
var errorHandler = require('./error-handler'); /**
* @class Client(options)
/* * @param {object} options configuration options for this instance
### function Client (options) * @description
#### @options {Object} Options for this instance * Constructor function for the Client base responsible for communicating with Challonge API
Constructor function for the Client base responsible */
for communicating with Challonge API const Client = exports.Client = function(options) {
*/
var Client = exports.Client = function(options) {
this.options = options || {}; this.options = options || {};
//defaults - todo convert to an object merge // defaults - todo convert to an object merge
if (!this.options.version) { if (!this.options.version) {
this.options.version = 1; this.options.version = 1;
} }
...@@ -27,7 +25,7 @@ var Client = exports.Client = function(options) { ...@@ -27,7 +25,7 @@ var Client = exports.Client = function(options) {
// add a getter to the options passed in - DO NOT mess with instance configs in resources // add a getter to the options passed in - DO NOT mess with instance configs in resources
if (typeof this.options.get !== 'function') { if (typeof this.options.get !== 'function') {
this.options.get = function(key) { this.options.get = function(key) { // not an arrow function to maintain "this" reference
return this[key]; return this[key];
}; };
} }
...@@ -35,17 +33,14 @@ var Client = exports.Client = function(options) { ...@@ -35,17 +33,14 @@ var Client = exports.Client = function(options) {
// serialize nested params to tournament[name] style // serialize nested params to tournament[name] style
function serializeProperties(obj) { function serializeProperties(obj) {
var compiledParams = ''; let compiledParams = '';
var serializedProperties = []; let serializedProperties = [];
for (var prop in obj) { for (let prop in obj) {
if (obj.hasOwnProperty(prop)) { if (obj.hasOwnProperty(prop) && typeof obj[prop] === 'object' && obj[prop] !== null) {
if (typeof (obj[prop]) === 'object' && obj[prop] !== null) { for (let attr in obj[prop]) {
for (var attr in obj[prop]) { compiledParams += '&' + prop + '[' + attr + ']=' + encodeURIComponent(obj[prop][attr]);
compiledParams += '&';
compiledParams += prop + '[' + attr + ']=' + encodeURIComponent(obj[prop][attr]);
}
serializedProperties.push(prop);
} }
serializedProperties.push(prop);
} }
} }
return { return {
...@@ -55,31 +50,29 @@ function serializeProperties(obj) { ...@@ -55,31 +50,29 @@ function serializeProperties(obj) {
} }
// resources generate props internal to https requests // resources generate props internal to https requests
var propertiesToDelete = ['callback', 'path', 'method']; let propertiesToDelete = ['callback', 'path', 'method'];
function camelToUnderscore(str) { function camelToUnderscore(str) {
return str.replace(/\W+/g, '-') return str.replace(/\W+/g, '-')
.replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase(); .replace(/([a-z\d])([A-Z])/g, '$1_$2')
.toLowerCase();
} }
function UnderscoreToCamel(str) { function UnderscoreToCamel(str) {
return str.replace(/_([a-z])/g, function(g) { return str.replace(/_([a-z])/g, g => g[1].toUpperCase());
return g[1].toUpperCase();
});
} }
function convertProperties(obj, converionFunction) { function convertProperties(obj, conversionFunction) {
//determine which we want to check with to see if we should convert // determine which we want to check with to see if we should convert
var checkRegex = converionFunction === UnderscoreToCamel ? /_/ : /[A-Z]/; const checkRegex = conversionFunction === UnderscoreToCamel ? /_/ : /[A-Z]/;
for (var prop in obj) { for (let prop in obj) {
if (obj.hasOwnProperty(prop)) { if (obj.hasOwnProperty(prop)) {
//objects recurse // objects recurse
if (typeof obj[prop] === 'object' && obj[prop] !== null) { if (typeof obj[prop] === 'object' && obj[prop] !== null) {
obj[converionFunction(prop)] = convertProperties(obj[prop], converionFunction); obj[conversionFunction(prop)] = convertProperties(obj[prop], conversionFunction);
} else if (prop.search(checkRegex) > -1) { } else if (prop.search(checkRegex) > -1) {
obj[converionFunction(prop)] = obj[prop]; obj[conversionFunction(prop)] = obj[prop];
//remove it delete obj[prop]; // remove it
delete obj[prop];
} }
//otherwise leave it alone //otherwise leave it alone
...@@ -89,7 +82,7 @@ function convertProperties(obj, converionFunction) { ...@@ -89,7 +82,7 @@ function convertProperties(obj, converionFunction) {
} }
Client.prototype.setSubdomain = function(subdomain) { Client.prototype.setSubdomain = function(subdomain) {
//generate the subdomain URL string if there is one // generate the subdomain URL string if there is one
if (!subdomain) { if (!subdomain) {
this.options.subdomain = ''; this.options.subdomain = '';
} else if (subdomain[subdomain.length - 1] !== '-') { } else if (subdomain[subdomain.length - 1] !== '-') {
...@@ -101,11 +94,11 @@ Client.prototype.setSubdomain = function(subdomain) { ...@@ -101,11 +94,11 @@ Client.prototype.setSubdomain = function(subdomain) {
// cleans the passed in object, generates the API url/query-string, makes the request, delegates errors and calls callbacks // cleans the passed in object, generates the API url/query-string, makes the request, delegates errors and calls callbacks
Client.prototype.makeRequest = function(obj) { Client.prototype.makeRequest = function(obj) {
var self = this; const self = this;
// cache vars that are about to be removed // cache vars that are about to be removed
var callback = obj.callback; const callback = obj.callback;
var path = obj.path; const method = obj.method;
var method = obj.method; let path = obj.path;
// normalize the rest of the properties // normalize the rest of the properties
obj = convertProperties(obj, camelToUnderscore); obj = convertProperties(obj, camelToUnderscore);
...@@ -113,25 +106,29 @@ Client.prototype.makeRequest = function(obj) { ...@@ -113,25 +106,29 @@ Client.prototype.makeRequest = function(obj) {
// Add on the api key // Add on the api key
obj.api_key = this.options.get('apiKey'); //convert for url obj.api_key = this.options.get('apiKey'); //convert for url
obj.cache_bust = Math.random(); obj.cache_bust = Math.random();
//serialize the properties
var serialized = serializeProperties(obj); // serialize the properties
var compiledParams = serialized.serialized; const serialized = serializeProperties(obj);
//merge the stuff to remove
// get the non-standard-formatted properties (this is to support the tournament[score] kind of params the api expects)
const compiledParams = serialized.serialized;
// merge the stuff to remove
propertiesToDelete = propertiesToDelete.concat(serialized.properties); propertiesToDelete = propertiesToDelete.concat(serialized.properties);
// remove params // remove params
propertiesToDelete.forEach(function(prop) { propertiesToDelete.forEach((prop) => {
delete obj[prop]; delete obj[prop];
}); });
// generate path // generate path
var versionPaths = { const versionPaths = {
1: '/v1/tournaments' 1: '/v1/tournaments'
}; };
path = versionPaths[this.options.get('version')] + (path ? path : '') + '.' + this.options.get('format') + '?' + qs.stringify(obj) + compiledParams; path = versionPaths[this.options.get('version')] + (path ? path : '') + '.' + this.options.get('format') + '?' + qs.stringify(obj) + compiledParams;
// create options for the https call // create options for the https call
var options = { const options = {
hostname: 'api.challonge.com', hostname: 'api.challonge.com',
path: path, path: path,
method: method, method: method,
...@@ -140,14 +137,14 @@ Client.prototype.makeRequest = function(obj) { ...@@ -140,14 +137,14 @@ Client.prototype.makeRequest = function(obj) {
} }
}; };
var req = https.request(options, function(res) { const req = https.request(options, (res) => {
// store the chunked data as it comes back // store the chunked data as it comes back
var resData = ''; let resData = '';
res.on('data', function(chunk) { res.on('data', (chunk) => {
resData += chunk; resData += chunk;
}); });
res.on('end', function() { res.on('end', () => {
// error // error
if (res.statusCode !== 200) { if (res.statusCode !== 200) {
errorHandler.handle(res, resData, callback, self.options.get('format')); errorHandler.handle(res, resData, callback, self.options.get('format'));
......
// Response Codes /**
// The following HTTP response codes are issued by the API. All other codes are the result of a request not reaching the application. * Response code handler
* @param {object} res the http response object
// 200 - OK * @param {object} resData the data contained in the response
// 401 - Invalid API key * @param {Function} callback the users callback function to call
// 404 - Object not found within your account scope * @param {string} format the format of the response data (json, xml, etc)
// 422 - Validation error(s) for create or update method * @description
* The following HTTP response codes are issued by the API.
* All other codes are the result of a request not reaching the application.
*/
exports.handle = function(res, resData, callback, format) { exports.handle = function(res, resData, callback, format) {
var err; let err;
// 401 - Invalid API key // 401 - Invalid API key
if (res.statusCode === 401) { if (res.statusCode === 401) {
err = { err = {
...@@ -34,7 +36,7 @@ exports.handle = function(res, resData, callback, format) { ...@@ -34,7 +36,7 @@ exports.handle = function(res, resData, callback, format) {
// 422 - Validation error(s) for create or update method // 422 - Validation error(s) for create or update method
if (res.statusCode === 422) { if (res.statusCode === 422) {
if (format == 'json') { if (format === 'json') {
resData = JSON.parse(resData); resData = JSON.parse(resData);
} }
err = { err = {
......
// index GET tournaments/:tournament/matches const util = require('util');
// show GET tournaments/:tournament/matches/:match_id const Client = require('./client').Client;
// update PUT tournaments/:tournament/matches/:match_id
var util = require('util'); /**
var Client = require('./client').Client; * @class Matches(options)
* @param {object} options configuration options for this instance
var Matches = exports.Matches = function(options) { * @description
* Constructor function for the class to query Matches endpoints
* index GET tournaments/:tournament/matches
* show GET tournaments/:tournament/matches/:match_id
* update PUT tournaments/:tournament/matches/:match_id
*/
const Matches = exports.Matches = function(options) {
Client.call(this, options); // call parent constructor Client.call(this, options); // call parent constructor
}; };
// Inherit from Client base object // inherit from Client base object
util.inherits(Matches, Client); util.inherits(Matches, Client);
Matches.prototype.index = function(obj) { Matches.prototype.index = function(obj) {
......
// index GET tournaments/:tournament/participants const util = require('util');
// create POST tournaments/:tournament/participants const Client = require('./client').Client;
// show GET tournaments/:tournament/participants/:participant_id
// update PUT tournaments/:tournament/participants/:participant_id
// destroy DELETE tournaments/:tournament/participants/:participant_id
// randomize GET tournaments/:tournament/participants/randomize
var util = require('util'); /**
var Client = require('./client').Client; * @class Participants(options)
* @param {object} options configuration options for this instance
var Participants = exports.Participants = function(options) { * @description
* Constructor function for the class to query Participants endpoints
* index GET tournaments/:tournament/participants
* create POST tournaments/:tournament/participants
* show GET tournaments/:tournament/participants/:participant_id
* update PUT tournaments/:tournament/participants/:participant_id
* destroy DELETE tournaments/:tournament/participants/:participant_id
* randomize GET tournaments/:tournament/participants/randomize
*/
const Participants = exports.Participants = function(options) {
Client.call(this, options); // call parent constructor Client.call(this, options); // call parent constructor
}; };
// Inherit from Client base object // inherit from Client base object
util.inherits(Participants, Client); util.inherits(Participants, Client);
Participants.prototype.index = function(obj) { Participants.prototype.index = function(obj) {
......
// // index GET tournaments const util = require('util');
// // create POST tournaments const Client = require('./client').Client;
// // show GET tournaments/:tournament
// // update PUT tournaments/:tournament
// // destroy DELETE tournaments/:tournament
// // start POST tournaments/:tournament/start
// // finalize POST tournaments/:tournament/finalize
// // reset POST tournaments/:tournament/reset
var util = require('util'); /**
var Client = require('./client').Client; * @class Participants(options)
* @param {object} options configuration options for this instance
var Tournaments = exports.Tournaments = function(options) { * @description
* Constructor function for the class to query Participants endpoints
* index GET tournaments
* create POST tournaments
* show GET tournaments/:tournament
* update PUT tournaments/:tournament
* destroy DELETE tournaments/:tournament
* start POST tournaments/:tournament/start
* finalize POST tournaments/:tournament/finalize
* reset POST tournaments/:tournament/reset
*/
const Tournaments = exports.Tournaments = function(options) {
Client.call(this, options); // call parent constructor Client.call(this, options); // call parent constructor
this.getRawSubdomain = function() { this.getRawSubdomain = function() {
...@@ -22,13 +27,11 @@ var Tournaments = exports.Tournaments = function(options) { ...@@ -22,13 +27,11 @@ var Tournaments = exports.Tournaments = function(options) {
}; };
}; };
// Inherit from Client base object // inherit from Client base object
util.inherits(Tournaments, Client); util.inherits(Tournaments, Client);
Tournaments.prototype.index = function(obj) { Tournaments.prototype.index = function(obj) {
obj.method = 'GET'; obj.method = 'GET';
// generate the subdomain property from the subdomain
// url we generate in the client constructor
if (this.getRawSubdomain()) { if (this.getRawSubdomain()) {
obj.subdomain = this.getRawSubdomain(); obj.subdomain = this.getRawSubdomain();
} }
...@@ -36,8 +39,6 @@ Tournaments.prototype.index = function(obj) { ...@@ -36,8 +39,6 @@ Tournaments.prototype.index = function(obj) {
}; };
Tournaments.prototype.create = function(obj) { Tournaments.prototype.create = function(obj) {
// generate the subdomain property from the subdomain
// url we generate in the client constructor
if (this.getRawSubdomain()) { if (this.getRawSubdomain()) {
obj.tournament.subdomain = this.getRawSubdomain(); obj.tournament.subdomain = this.getRawSubdomain();
} }
......
'use strict'; const endpoints = ['Client', 'Tournaments', 'Participants', 'Matches'];
var parts = ['Client', 'Tournaments', 'Participants', 'Matches']; endpoints.forEach(endpointName => {
exports[endpointName] = require('./api/' + endpointName.toLowerCase())[endpointName];
parts.forEach(function forEach(k) {
exports[k] = require('./api/' + k.toLowerCase())[k];
}); });
/* /**
### function createClient(options) * @function createClient(options)
#### @options {Object} options for the clients * @param {object} options configuration options for this instance
Generates a new API client. * @returns {object} new api client instance
*/ * @description
* Generates a new API client.
*/
exports.createClient = function createClient(options) { exports.createClient = function createClient(options) {
var client = {}; const client = {};
// require each lib in ./api and instantiate a new instance of each object, passing the options we were passed // require each lib in ./api and instantiate a new instance of each object, passing the options we were passed
parts.forEach(function generate(k) { endpoints.forEach(endpointName => {
var endpoint = k.toLowerCase(); // store for the user to reference via instance.resource
client[endpoint] = new exports[k](options); // store for the user to reference via instance.resource client[endpointName.toLowerCase()] = new exports[endpointName](options);
}); });
client.setSubdomain = function(subdomain) { client.setSubdomain = subdomain => {
parts.forEach(function update(k) { endpoints.forEach(endpointName => {
var endpoint = k.toLowerCase(); client[endpointName.toLowerCase()].setSubdomain(subdomain);
client[endpoint].setSubdomain(subdomain);
}); });
}; };
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"description": "Wrapper for the challong api", "description": "Wrapper for the challong api",
"author": "Aaron Tiwell <aaron.tidwell@gmail.com>", "author": "Aaron Tiwell <aaron.tidwell@gmail.com>",
"main": "./lib/challonge.js", "main": "./lib/challonge.js",
"version": "1.2.0", "version": "2.0.0",
"contributors": [ "contributors": [
{ {
"name": "Ricardo Reis", "name": "Ricardo Reis",
...@@ -49,5 +49,5 @@ ...@@ -49,5 +49,5 @@
"integrate": "npm run-script test && npm run-script format && npm run-script lint" "integrate": "npm run-script test && npm run-script format && npm run-script lint"
}, },
"engine": "node >= 0.10.x" "engine": "node >= 6.0.x"
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment