Skip to content
This repository has been archived by the owner on Jan 19, 2024. It is now read-only.

Jscs/Test clean up #52

Merged
merged 4 commits into from
May 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions .jscsrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"disallowCommaBeforeLineBreak": true,
"disallowEmptyBlocks": true,
"disallowImplicitTypeConversion": ["numeric", "binary", "string"],
"disallowKeywordsOnNewLine": ["else", "else if", "switch", "for", "while"],
"disallowMixedSpacesAndTabs": true,
"disallowMultipleLineBreaks": true,
"disallowMultipleLineStrings": true,
"disallowNamedUnassignedFunctions": true,
"disallowNewlineBeforeBlockStatements": true,
"disallowOperatorBeforeLineBreak": ["+", "."],
"disallowSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"disallowSpacesInCallExpression": true,

"requireAnonymousFunctions": true,
"requireBlocksOnNewline": true,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"requireCapitalizedConstructors": true,
"requireCurlyBraces": [
"if",
"else",
"for",
"while",
"do",
"try",
"catch",
"case",
"default"
],
"requireDotNotation": true,
"requirePaddingNewLineAfterVariableDeclaration": true,
"requirePaddingNewLinesAfterUseStrict": true,
"requirePaddingNewLinesBeforeExport": true,
"requireSemicolons": true,
"requireSpaceBeforeBlockStatements": true,
"requireSpaceBeforeKeywords": [
"else",
"while",
"catch"
],
"requireSpaceBeforeObjectValues": true,
"requireSpaceBetweenArguments": true,
"requireSpacesInAnonymousFunctionExpression": {
"beforeOpeningCurlyBrace": true
},
"requireSpacesInFunctionDeclaration": {
"beforeOpeningCurlyBrace": true
},
"requireSpacesInFunctionExpression": {
"beforeOpeningCurlyBrace": true
}
}
1 change: 1 addition & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"globals": {
"require": true,
"before": true,
"beforeEach": true,
"after": true,
"define": true,
"describe": true,
Expand Down
26 changes: 19 additions & 7 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/

module.exports = function( grunt ) {
module.exports = function(grunt) {
'use strict';

grunt.initConfig({
Expand All @@ -41,11 +41,11 @@ module.exports = function( grunt ) {
}
, bump: {
options: {
files: [ 'package.json' ]
, updateConfigs: [ 'pkg' ]
files: ['package.json']
, updateConfigs: ['pkg']
, commit: true
, commitMessage: 'Release %VERSION%'
, commitFiles: [ 'package.json', 'README.md' ]
, commitFiles: ['package.json', 'README.md']
, createTag: true
, tagName: '%VERSION%'
, tagMessage: '%VERSION%'
Expand All @@ -54,9 +54,21 @@ module.exports = function( grunt ) {
, gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
}
}
, jscs: {
src: [
'lib/*.js',
'test/**/*.js'
],
options: {
config: '.jscsrc',
esnext: true, // If you use ES6 http://jscs.info/overview.html#esnext
verbose: true // If you need output with rule names http://jscs.info/overview.html#verbose
}
}
});

grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-bump' );
grunt.registerTask( 'default', [ 'jshint' ] );
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-jscs');
grunt.registerTask('default', ['jshint', 'jscs']);
};
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ npm install fuel-rest --save

## Initialization

**new FuelRest( options )** - Initialization
**new FuelRest(options)** - Initialization

* `options.auth`
* Required: yes
Expand All @@ -26,13 +26,13 @@ npm install fuel-rest --save

## API

* **apiRequest( options, callback )**
* **apiRequest(options, callback)**
* `options` - [see request modules options][3]
* `options.auth` - will be passed into [getAccessToken][4] inside Fuel Auth
* `options.uri` - can either be a full url or a path that is appended to `options.origin` used at initialization ([url.resolve][2])
* `options.retry` - boolean value representing whether or not to retry request (and request new token) on 401 invalid token response. `default: false`
* `callback` - executed after task is completed. **required**
* **get | post | put | patch | delete( options, callback )**
* **get | post | put | patch | delete(options, callback)**
* `options` - see apiRequest options
* `options.retry` - see above for description. `default: true`
* `callback` - see apiRequest options
Expand All @@ -41,7 +41,7 @@ npm install fuel-rest --save
## Setting up the client

```js
var FuelRest = require( 'fuel-rest' );
var FuelRest = require('fuel-rest');
var options = {
auth: {
// options you want passed when Fuel Auth is initialized
Expand All @@ -51,7 +51,7 @@ var options = {
, origin: 'https://alternate.rest.endpoint.com' // default --> https://www.exacttargetapis.com
};

var RestClient = new FuelRest( options );
var RestClient = new FuelRest(options);
```


Expand All @@ -64,16 +64,16 @@ var options = {
// other request options
};

RestClient.get( options, function( err, response ) {
if( err ) {
RestClient.get(options, function(err, response) {
if(err) {
// error here
console.log( err );
console.log(err);
}

// will be delivered with 200, 400, 401, 500, etc status codes
// response.body === payload from response
// response.res === full response from request client
console.log( response );
console.log(response);
});
```

Expand Down
93 changes: 45 additions & 48 deletions lib/fuel-rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,24 @@
* POSSIBILITY OF SUCH DAMAGE.
*/

var version = require( '../package.json').version;
var helpers = require( './helpers' );
var request = require( 'request');
var _ = require( 'lodash' );
var FuelAuth = require( 'fuel-auth' );
var version = require('../package.json').version;
var helpers = require('./helpers');
var request = require('request');
var _ = require('lodash');
var FuelAuth = require('fuel-auth');


var FuelRest = function( options ) {
var FuelRest = function(options) {
'use strict';

var authOptions = options && options.auth || {};

// use fuel auth instance if applicable
if( authOptions instanceof FuelAuth ) {
if(authOptions instanceof FuelAuth) {
this.AuthClient = authOptions;
} else {
try {
this.AuthClient = new FuelAuth( authOptions );
} catch( err ) {
this.AuthClient = new FuelAuth(authOptions);
} catch(err) {
throw err;
}
}
Expand All @@ -59,131 +58,129 @@ var FuelRest = function( options ) {
this.origin = options.origin || options.restEndpoint || 'https://www.exacttargetapis.com';
};

FuelRest.prototype.apiRequest = function( options, callback ) {
FuelRest.prototype.apiRequest = function(options, callback) {
'use strict';

// we need a callback
if( !_.isFunction( callback ) ) {
throw new TypeError( 'callback argument is required' );
if(!_.isFunction(callback)) {
throw new TypeError('callback argument is required');
}

// we need options
if( !_.isPlainObject( options ) ) {
throw new TypeError( 'options argument is required' );
if(!_.isPlainObject(options)) {
throw new TypeError('options argument is required');
}

this.AuthClient.getAccessToken( _.clone( options.auth ), function( err, body ) {
this.AuthClient.getAccessToken(_.clone(options.auth), function(err, body) {
var localError, retry, authOptions;

if( err ) {
helpers.respond( 'error', err, callback, 'FuelAuth' );
if(err) {
helpers.respond('error', err, callback, 'FuelAuth');
return;
}

// if there's no access token we have a problem
if( !body.accessToken ) {
localError = new Error( 'No access token' );
if(!body.accessToken) {
localError = new Error('No access token');
localError.res = body;
helpers.respond( 'error', localError, callback, 'FuelAuth' );
helpers.respond('error', localError, callback, 'FuelAuth');
return;
}

// retry request?
retry = options.retry || false;
authOptions = _.clone( options.auth );
authOptions = _.clone(options.auth);

// clean up
delete options.retry;
delete options.auth;

// if we don't have a fully qualified URL let's make one
options.uri = helpers.resolveUri( this.origin, options.uri );
options.uri = helpers.resolveUri(this.origin, options.uri);

// merge headers
options.headers = _.merge( {}, this.defaultHeaders, options.headers );
options.headers = _.merge({}, this.defaultHeaders, options.headers);

// adding the bearer token
options.headers.Authorization = options.headers.Authorization || 'Bearer ' + body.accessToken;

// send request to api
request( options, function( err, res, body ) {
request(options, function(err, res, body) {
var parsedBody;

if( err ) {
helpers.respond( 'error', err, callback, 'Request Module inside apiRequest' );
if(err) {
helpers.respond('error', err, callback, 'Request Module inside apiRequest');
return;
}

// check if we should retry req
if( helpers.check401header( res ) && !!retry ) {
if(helpers.check401header(res) && !!retry) {
options.auth = authOptions;
this.apiRequest( options, callback );
this.apiRequest(options, callback);
return;
}

// checking to make sure it's json from api
if( !res.headers[ 'content-type' ] || res.headers[ 'content-type' ].split( ';' )[ 0 ].toLowerCase() !== 'application/json' ) {
helpers.respond( 'error', new Error( 'API did not return JSON' ), callback, 'Fuel REST' );
if(!res.headers['content-type'] || res.headers['content-type'].split(';')[0].toLowerCase() !== 'application/json') {
helpers.respond('error', new Error('API did not return JSON'), callback, 'Fuel REST');
return;
}

// trying to parse body
try {
parsedBody = JSON.parse( body );
} catch( err ) {
parsedBody = JSON.parse(body);
} catch(err) {
parsedBody = body;
}

helpers.respond( 'response', { res: res, body: parsedBody }, callback );

}.bind( this ) );

}.bind( this ) );
helpers.respond('response', { res: res, body: parsedBody }, callback);
}.bind(this));
}.bind(this));
};

FuelRest.prototype.get = function( options, callback ) {
FuelRest.prototype.get = function(options, callback) {
'use strict';

options.method = 'GET';
options.retry = true;

this.apiRequest( options, callback );
this.apiRequest(options, callback);
};

FuelRest.prototype.post = function( options, callback ) {
FuelRest.prototype.post = function(options, callback) {
'use strict';

options.method = 'POST';
options.retry = true;

this.apiRequest( options, callback );
this.apiRequest(options, callback);
};

FuelRest.prototype.put = function( options, callback ) {
FuelRest.prototype.put = function(options, callback) {
'use strict';

options.method = 'PUT';
options.retry = true;

this.apiRequest( options, callback );
this.apiRequest(options, callback);
};

FuelRest.prototype.patch = function( options, callback ) {
FuelRest.prototype.patch = function(options, callback) {
'use strict';

options.method = 'PATCH';
options.retry = true;

this.apiRequest( options, callback );
this.apiRequest(options, callback);
};

FuelRest.prototype.delete = function( options, callback ) {
FuelRest.prototype.delete = function(options, callback) {
'use strict';

options.method = 'DELETE';
options.retry = true;

this.apiRequest( options, callback );
this.apiRequest(options, callback);
};

module.exports = FuelRest;
Loading