Commit a8c818eb authored by Aaron Tidwell's avatar Aaron Tidwell

update to const/let and resolve formatting issues

parent 91559004
......@@ -15,7 +15,6 @@ var client = challonge.createClient({
apiKey: '***yourAPIKey***'
});
client.tournaments.index({
callback: function(err, data){
if (err) { console.log(err); return; }
......
'use strict';
var qs = require('querystring');
var https = require('https');
var errorHandler = require('./error-handler');
/*
### function Client (options)
#### @options {Object} Options for this instance
Constructor function for the Client base responsible
for communicating with Challonge API
*/
var Client = exports.Client = function(options) {
const qs = require('querystring');
const https = require('https');
const errorHandler = require('./error-handler');
/**
* @class Client(options)
* @param {object} options configuration options for this instance
* @description
* Constructor function for the Client base responsible for communicating with Challonge API
*/
const Client = exports.Client = function(options) {
this.options = options || {};
//defaults - todo convert to an object merge
// defaults - todo convert to an object merge
if (!this.options.version) {
this.options.version = 1;
}
......@@ -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
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];
};
}
......@@ -35,19 +33,16 @@ var Client = exports.Client = function(options) {
// serialize nested params to tournament[name] style
function serializeProperties(obj) {
var compiledParams = '';
var serializedProperties = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof (obj[prop]) === 'object' && obj[prop] !== null) {
for (var attr in obj[prop]) {
compiledParams += '&';
compiledParams += prop + '[' + attr + ']=' + encodeURIComponent(obj[prop][attr]);
let compiledParams = '';
let serializedProperties = [];
for (let prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] === 'object' && obj[prop] !== null) {
for (let attr in obj[prop]) {
compiledParams += '&' + prop + '[' + attr + ']=' + encodeURIComponent(obj[prop][attr]);
}
serializedProperties.push(prop);
}
}
}
return {
serialized: compiledParams,
properties: serializedProperties
......@@ -55,31 +50,29 @@ function serializeProperties(obj) {
}
// resources generate props internal to https requests
var propertiesToDelete = ['callback', 'path', 'method'];
let propertiesToDelete = ['callback', 'path', 'method'];
function camelToUnderscore(str) {
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) {
return str.replace(/_([a-z])/g, function(g) {
return g[1].toUpperCase();
});
return str.replace(/_([a-z])/g, g => g[1].toUpperCase());
}
function convertProperties(obj, converionFunction) {
//determine which we want to check with to see if we should convert
var checkRegex = converionFunction === UnderscoreToCamel ? /_/ : /[A-Z]/;
for (var prop in obj) {
function convertProperties(obj, conversionFunction) {
// determine which we want to check with to see if we should convert
const checkRegex = conversionFunction === UnderscoreToCamel ? /_/ : /[A-Z]/;
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
//objects recurse
// objects recurse
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) {
obj[converionFunction(prop)] = obj[prop];
//remove it
delete obj[prop];
obj[conversionFunction(prop)] = obj[prop];
delete obj[prop]; // remove it
}
//otherwise leave it alone
......@@ -89,7 +82,7 @@ function convertProperties(obj, converionFunction) {
}
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) {
this.options.subdomain = '';
} else if (subdomain[subdomain.length - 1] !== '-') {
......@@ -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
Client.prototype.makeRequest = function(obj) {
var self = this;
const self = this;
// cache vars that are about to be removed
var callback = obj.callback;
var path = obj.path;
var method = obj.method;
const callback = obj.callback;
const method = obj.method;
let path = obj.path;
// normalize the rest of the properties
obj = convertProperties(obj, camelToUnderscore);
......@@ -113,25 +106,29 @@ Client.prototype.makeRequest = function(obj) {
// Add on the api key
obj.api_key = this.options.get('apiKey'); //convert for url
obj.cache_bust = Math.random();
//serialize the properties
var serialized = serializeProperties(obj);
var compiledParams = serialized.serialized;
//merge the stuff to remove
// serialize the properties
const serialized = serializeProperties(obj);
// 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);
// remove params
propertiesToDelete.forEach(function(prop) {
propertiesToDelete.forEach((prop) => {
delete obj[prop];
});
// generate path
var versionPaths = {
const versionPaths = {
1: '/v1/tournaments'
};
path = versionPaths[this.options.get('version')] + (path ? path : '') + '.' + this.options.get('format') + '?' + qs.stringify(obj) + compiledParams;
// create options for the https call
var options = {
const options = {
hostname: 'api.challonge.com',
path: path,
method: method,
......@@ -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
var resData = '';
res.on('data', function(chunk) {
let resData = '';
res.on('data', (chunk) => {
resData += chunk;
});
res.on('end', function() {
res.on('end', () => {
// error
if (res.statusCode !== 200) {
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.
// 200 - OK
// 401 - Invalid API key
// 404 - Object not found within your account scope
// 422 - Validation error(s) for create or update method
/**
* Response code handler
* @param {object} res the http response object
* @param {object} resData the data contained in the response
* @param {Function} callback the users callback function to call
* @param {string} format the format of the response data (json, xml, etc)
* @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) {
var err;
let err;
// 401 - Invalid API key
if (res.statusCode === 401) {
err = {
......@@ -34,7 +36,7 @@ exports.handle = function(res, resData, callback, format) {
// 422 - Validation error(s) for create or update method
if (res.statusCode === 422) {
if (format == 'json') {
if (format === 'json') {
resData = JSON.parse(resData);
}
err = {
......
// index GET tournaments/:tournament/matches
// show GET tournaments/:tournament/matches/:match_id
// update PUT tournaments/:tournament/matches/:match_id
const util = require('util');
const Client = require('./client').Client;
var util = require('util');
var Client = require('./client').Client;
var Matches = exports.Matches = function(options) {
/**
* @class Matches(options)
* @param {object} options configuration options for this instance
* @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
};
// Inherit from Client base object
// inherit from Client base object
util.inherits(Matches, Client);
Matches.prototype.index = function(obj) {
......
// 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 util = require('util');
const Client = require('./client').Client;
var util = require('util');
var Client = require('./client').Client;
var Participants = exports.Participants = function(options) {
/**
* @class Participants(options)
* @param {object} options configuration options for this instance
* @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
};
// Inherit from Client base object
// inherit from Client base object
util.inherits(Participants, Client);
Participants.prototype.index = function(obj) {
......
// // 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 util = require('util');
const Client = require('./client').Client;
var util = require('util');
var Client = require('./client').Client;
var Tournaments = exports.Tournaments = function(options) {
/**
* @class Participants(options)
* @param {object} options configuration options for this instance
* @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
this.getRawSubdomain = function() {
......@@ -22,13 +27,11 @@ var Tournaments = exports.Tournaments = function(options) {
};
};
// Inherit from Client base object
// inherit from Client base object
util.inherits(Tournaments, Client);
Tournaments.prototype.index = function(obj) {
obj.method = 'GET';
// generate the subdomain property from the subdomain
// url we generate in the client constructor
if (this.getRawSubdomain()) {
obj.subdomain = this.getRawSubdomain();
}
......@@ -36,8 +39,6 @@ Tournaments.prototype.index = function(obj) {
};
Tournaments.prototype.create = function(obj) {
// generate the subdomain property from the subdomain
// url we generate in the client constructor
if (this.getRawSubdomain()) {
obj.tournament.subdomain = this.getRawSubdomain();
}
......
'use strict';
const endpoints = ['Client', 'Tournaments', 'Participants', 'Matches'];
var parts = ['Client', 'Tournaments', 'Participants', 'Matches'];
parts.forEach(function forEach(k) {
exports[k] = require('./api/' + k.toLowerCase())[k];
endpoints.forEach(endpointName => {
exports[endpointName] = require('./api/' + endpointName.toLowerCase())[endpointName];
});
/*
### function createClient(options)
#### @options {Object} options for the clients
Generates a new API client.
*/
/**
* @function createClient(options)
* @param {object} options configuration options for this instance
* @returns {object} new api client instance
* @description
* Generates a new API client.
*/
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
parts.forEach(function generate(k) {
var endpoint = k.toLowerCase();
client[endpoint] = new exports[k](options); // store for the user to reference via instance.resource
endpoints.forEach(endpointName => {
// store for the user to reference via instance.resource
client[endpointName.toLowerCase()] = new exports[endpointName](options);
});
client.setSubdomain = function(subdomain) {
parts.forEach(function update(k) {
var endpoint = k.toLowerCase();
client[endpoint].setSubdomain(subdomain);
client.setSubdomain = subdomain => {
endpoints.forEach(endpointName => {
client[endpointName.toLowerCase()].setSubdomain(subdomain);
});
};
......
......@@ -3,7 +3,7 @@
"description": "Wrapper for the challong api",
"author": "Aaron Tiwell <aaron.tidwell@gmail.com>",
"main": "./lib/challonge.js",
"version": "1.2.0",
"version": "2.0.0",
"contributors": [
{
"name": "Ricardo Reis",
......@@ -49,5 +49,5 @@
"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