Code coverage report for lib/shared/BaseRequest.js

Statements: 86.73% (98 / 113)      Branches: 76.67% (46 / 60)      Functions: 95.24% (20 / 21)      Lines: 86.73% (98 / 113)      Ignored: none     

All files » lib/shared/ » BaseRequest.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290            29 29 29                         1 66   66   66   66                 1       1 9         1 164                     1 164 164 164   164     158     158                       1 149       1                                     29 165                   29   169 169 169   169 143   169         29 168 142   168             1 210 210                                                   29 210 210   210         29   210       210   210                 29 119 119 119   119 1   118       29 18 18 18   18 2 2   16     18 4   14       29 5 5 5   5       5     5 1   4       29 6 6 6   6       6     6 1   5       29 12 12 12   12 1   11       29 4 4 4   4 1   3       29
'use strict';
 
/**
* @module BaseRequest
**/
 
var Promise = require('bluebird');
var agent = require('superagent');
var Route = require('route-parser');
 
 
/**
 * BaseRequest is the base API request object constructor
 *
 * @class BaseRequest
 * @constructor
 * @param {Object} options - A hash of options for the BaseRequest instance
 * @param {String} options.endpoint - The endpoint URI to request
 * @param {String} [options.username] - A username for authenticating API requests
 * @param {String} [options.password] - A password for authenticating API requests
 */
 function BaseRequest(options) {
    this._options = options || {};
    // hash of key,val pairs to get the URL to request by expanding the this._template
    this._path = {};
    // the template that the different URL endpoints for a given class follows
    this._template = '';
    // the BaseRequest should support all the possible methods
    this._supportedMethods = [ 'head', 'get', 'put', 'post', 'delete', 'patch' ];
 
 }
 
/** 
* Utility functions that are used by invokeAndPromisify
**/
 
// function that does not perform any operation
 function noop() { }
 
 
 // function that simply returns the input value to it
 function identity(input) {
    return input;
 }
 
 
// check if the "func" is a function or 
 function ensureCallback(func) {
    return ( typeof func === 'function' ) ? func : noop;
}
 
 
// the API should offer support for both callbacks and promises
// so promisify and invoke the request 
/*
* @param {Function} callback - The promise callback
* @param {Object} request - Request object to invoke
* @param {Function} transform - Transform operation to be carried on the response
*/
function invokeandPromisify(request, callback, transform) {
    callback = ensureCallback( callback );
    transform = transform || identity;
    return new Promise(function(resolve,reject) {
    // Invoke the request
    request.end(function(err,result) {
 
        // Return the results as a promise
        Iif (err || result.error) {
            reject(err || result.error);
        } else {
            resolve(result);
        }
    });
    }).then(transform).nodeify(callback);
}
 
 
/*
** Some transform functions
*/
 
// returns the body of the result from the agent call
function getBody(result) {
    return result.body;
}
 
// returns the headers of the result from the agent call
function getHeaders(result) {
    return result.headers;
}
 
 
/*
Prototype methods
=================
*/
 
/**
 * Verify that the current request object supports a given HTTP verb
 *
 * @private
 *
 * @method _checkMethodSupport
 * @param {String} method An HTTP method to check ('get', 'post', etc)
 * @return true iff the method is within this._supportedMethods
 */
BaseRequest.prototype._checkMethodSupport = function(method) {
    Iif ( this._supportedMethods.indexOf(method) == -1 ) {
        throw new Error(
            'Unsupported method, Supported methods are:'+
            this._supportedMethods.join(',')
        );
    }
}
 
 
// Check presence of authentication parameters
BaseRequest.prototype._checkAuthParameters = function() {
    // by default assuming the authentication is not requires
    this._options.forceAuth = false;
    var username = this._options.username || null;
    var password = this._options.password || null;
    // force the authentication is the username and password is supplied
    if ( typeof username === 'string' && typeof password === 'string' ) {
        this._options.forceAuth = true;
    }
    return this._options.forceAuth;
}
 
 
// handles authentication automatically by taking a request object as parameter
BaseRequest.prototype._auth  = function(request) {
    if ( this._checkAuthParameters() ) {
        request.auth(this._options.username,this._options.password);
    }
    return request;
}
 
 
/* TODO : add validators */
 
// check if anything is not validating before rendering the final URI
function validatePath(pathObj,validatorObj) {
    Eif (!validatorObj) {
        return pathObj;
    }
 
    for(var prop in pathObj) {
 
        if(!pathObj.hasOwnProperty(prop)) {
            continue;
        }
 
        if (!validatorObj[prop]) {
            // no validator, no issue
            continue;
        }
 
        if ( !(pathObj[prop]+'').match(validatorObj[prop]) ) {
            throw new Error (
                prop + 'does not match' + validatorObj[prop]
            );
        }
 
        return pathObj;
    }
}
 
 
// render the path to request
BaseRequest.prototype._renderPath = function() {
    var pathTemplate = new Route(this._template);
    var validatedPath = validatePath(this._path,this._pathValidators);
 
    return pathTemplate.reverse(validatedPath) || '';
}
 
 
// render final URI to request by checking for the query params
BaseRequest.prototype._renderURI = function() {
    // Render the path to a string
    var path = this._renderPath();
 
    // If the current request supports query params, render them to a query string
    // => set this._renderQuery to true when query params are added
    var queryStr = this._queryParams ? ('?' + this._renderQuery()) : '';
 
    return this._options.endpoint + path + queryStr;
};
 
/*
 HTTP methods
 ============
 */
 
 
BaseRequest.prototype.get = function(callback,transform) {
    var url = this._renderURI();
    this._checkMethodSupport('get');
    var request = this._auth(agent.get(url));
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
BaseRequest.prototype.post = function(data,callback,transform) {
    var request;
    var url = this._renderURI();
    this._checkMethodSupport('post');
 
    if ( typeof data === 'undefined' || JSON.stringify(data) === '{}' )  { 
        data = {};
        request = this._auth(agent.post(url)).send(data); 
    } else {
        request = this._auth(agent.post(url)).send(data).type('form');
    }
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
BaseRequest.prototype.put = function(data,callback,transform) {
    var request;
    var url = this._renderURI();
    this._checkMethodSupport('put');
 
    Iif ( typeof data === 'undefined' || JSON.stringify(data) === '{}' )  { 
        data = {};
        request = this._auth(agent.put(url)).send(data); 
    } else {
        request = this._auth(agent.put(url)).send(data).type('form');
    }
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
BaseRequest.prototype.patch = function(data,callback,transform) {
    var request;
    var url = this._renderURI();
    this._checkMethodSupport('patch');
 
    Iif ( typeof data === 'undefined' || JSON.stringify(data) === '{}' )  { 
        data = {};
        request = this._auth(agent.patch(url)).send(data); 
    } else {
        request = this._auth(agent.patch(url)).send(data).type('form');
    }
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
BaseRequest.prototype.delete = function(callback,transform) {
    var url = this._renderURI();
    this._checkMethodSupport('delete');
    var request = this._auth(agent.del(url));
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
BaseRequest.prototype.head = function(callback,transform) {
    var url = this._renderURI();
    this._checkMethodSupport('head');
    var request = this._auth(agent.head(url));
 
    if ( transform === 'identity' )
        return invokeandPromisify(request,callback,identity);
    else
        return invokeandPromisify(request,callback,getBody);
}
 
 
module.exports = BaseRequest;