Code coverage report for lib/shared/ApiRequest.js

Statements: 100% (25 / 25)      Branches: 100% (15 / 15)      Functions: 100% (4 / 4)      Lines: 100% (25 / 25)      Ignored: none     

All files » lib/shared/ » ApiRequest.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          1 1 1       1 20   20   20       1                     1 14   14 5     9   8 15 14     1             1           12   12         1 6   6         6       1
'use strict';
 
/**
* @module ApiRequest
**/
var BaseRequest = require('./BaseRequest');
var lodash = require('lodash');
var qs = require('qs');
 
 
// This class add properties to add and render URI query parameters
 function ApiRequest(options) {
    this._options = options || {};
    // the query parameters
    this._params = {};
    // flag to check whether it is required to render the query parameters or not
    this._queryParams = false;
 }
 
 
 ApiRequest.prototype = new BaseRequest();
 
 
 /*
@key
    can be a object with key,value pairs
    can be a key string 
@value
    can be an array
    can be a string value
 */
ApiRequest.prototype.query = function(key,value) { 
    var that = this; 
 
    if ( lodash.isString(key) && (lodash.isArray(value) || lodash.isString(value)) ) {
        this._params[key] = value;
    }
    // key is only supplied as object
    else if ( lodash.isObject(key) && !value ) { 
        // iterating over key,value pair of the key Object
        lodash.each(key,function(v,k) {
            if ( lodash.isArray(v) || lodash.isString(v) ) {
                that._params[k] = v;
            }
            else {
                throw new Error(
                    "Unsupported object supplied, keys should be of type String and Value should be of type String/Array."
                );
            }
        });
    }
    else {
        throw new Error(
            'Arguments not found in the required form.'
            );
    }
 
    // if no error, means query parameters are required to be rendered
    this._queryParams = true;
    // return the ApiRequest intance
    return this;
 }
 
 
// function to render the query in the request URI
ApiRequest.prototype._renderQuery = function() {
    var queryParams = this._params;
    // sorting is done to probably cache the URIs
    var queryString = qs.stringify(this._params)
        .split( '&' )
        .sort()
        .join( '&' );
 
    return queryString;
}
 
 
module.exports = ApiRequest;