all files / lib/ najax.js

84.35% Statements 97/115
77.53% Branches 69/89
86.67% Functions 13/15
84.35% Lines 97/115
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          1× 1× 1× 1× 1× 1× 1× 1×                   1× 3×     1× 49× 49× 28×   21×   49× 98× 48×     49× 7×   49×       1× 4× 38× 38× 38×         1×                   61×   61× 11×     50× 50× 50× 50× 50×             50× 1× 49× 2×   1× 1×   1× 1×             50× 5× 1×     1×       4×             50×                     50× 5× 45× 5× 40× 5×     50×     50×           1× 200×           50×                   1×   1×   1×       1×     50×   49×     49× 49×   49× 49× 49×                 49× 49×   49×   49×           49×   49× 49×   49×   49×   49× 49×     49×                             50×     50× 1× 1× 1× 1×   1×       1×           50× 4×   50×     50× 50× 50×    
/* najax
 * jquery ajax-stye http requests in node
 * https://github.com/alanclarke/najax
 */
 
var https = require('https')
var http = require('http')
var querystring = require('querystring')
var url = require('url')
var $ = require('jquery-deferred')
var _ = require('lodash')
var najax = module.exports = request
var default_settings = {
  method: 'GET',
  rejectUnauthorized: true,
  processData: true,
  data: '',
  contentType: 'application/x-www-form-urlencoded',
  headers: {}
}
 
/* set default settings */
module.exports.defaults = function (opts) {
  return _.extend(default_settings, opts)
}
 
function _parseOptions (options, a, b) {
  var opts = _.extend({}, default_settings)
  if (_.isString(options)) {
    opts.url = options
  } else {
    _.extend(opts, options)
  }
  _.each([a, b], function (fn) {
    if (_.isFunction(fn)) {
      opts.success = fn
    }
  })
  if (!_.isFunction(a)) {
    _.extend(opts, a)
  }
  return opts
}
 
/* auto rest interface go! */
_.each('get post put delete'.split(' '), function (method) {
  najax[method] = module.exports[method] = function (options, a, b) {
    var opts = _parseOptions(options, a, b)
    opts.method = method.toUpperCase()
    return najax(opts)
  }
})
 
/* main function definition */
function request (options, a, b) {
  // OPTIONS
  /*
  	method overloading, can use:
    -function(url, opts, callback) or
    -function(url, callback)
    -function(opts)
  */
 
  // support legacy jquery options.type
  options.method = options.method || options.type
 
  if (_.isString(options) || _.isFunction(a)) {
    return request(_parseOptions(options, a, b))
  }
 
  var dfd = new $.Deferred()
  var o = _.extend({}, default_settings, options)
  var l = url.parse(o.url)
  var ssl = l.protocol.indexOf('https') === 0
  var data = ''
 
  // DATA
  // Per jquery docs / source: encoding is only done
  // if processData is true (defaults to true)
  // and the data is not already a string
  // https://github.com/jquery/jquery/blob/master/src/ajax.js#L518
  if (o.data && o.processData && o.method === 'GET') {
    o.data = querystring.stringify(o.data)
  } else if (o.data && o.processData && typeof o.data !== 'string' && o.method !== 'GET') {
    switch (o.contentType) {
      case 'application/json':
        o.data = JSON.stringify(o.data)
        break
      case 'application/x-www-form-urlencoded':
        o.data = querystring.stringify(o.data)
        break
      default:
        o.data = o.data.toString()
    }
  }
 
  /* if get, use querystring method for data */
  if (o.data) {
    if (o.method === 'GET') {
      Iif (l.search) {
        l.search += '&' + o.data
      } else {
        l.search = '?' + o.data
      }
    } else {
      /* set data content type */
      o.headers = _.extend({
        'Content-Type': o.contentType + ';charset=utf-8',
        'Content-Length': Buffer.byteLength(o.data)
      }, o.headers)
    }
  }
 
  options = {
    host: l.hostname,
    path: l.pathname + (l.search || ''),
    method: o.method,
    port: Number(l.port) || (ssl ? 443 : 80),
    headers: o.headers,
    rejectUnauthorized: o.rejectUnauthorized
  }
 
  // AUTHENTICATION
  /* add authentication to http request */
  if (l.auth) {
    options.auth = l.auth
  } else if (o.username && o.password) {
    options.auth = o.username + ':' + o.password
  } else if (o.auth) {
    options.auth = o.auth
  }
 
  _.extend(options, _.pick(o, ['auth', 'agent']))
 
  /* for debugging, method to get options and return */
  Iif (o.getopts) {
    var getopts = [ssl, options, o.data || false, o.success || false, o.error || false]
    return getopts
  }
 
  // REQUEST
  function notImplemented (name) {
    return function () {
      console.error('najax: method jqXHR."' + name + '" not implemented')
      console.trace()
    }
  }
 
  var jqXHR = {
    readyState: 0,
    status: 0,
    statusText: 'error', // one of: "success", "notmodified", "error", "timeout", "abort", or "parsererror"
    setRequestHeader: notImplemented('setRequestHeader'),
    getAllResponseHeaders: notImplemented('getAllResponseHeaders'),
    statusCode: notImplemented('statusCode'),
    abort: notImplemented('abort')
  }
 
  function errorHandler (e) {
    // Set data for the fake xhr object
    jqXHR.responseText = e.stack
 
    Iif (_.isFunction(o.error)) {
      o.error(jqXHR, 'error', e)
    }
    // jqXHR, statusText, error
    dfd.reject(jqXHR, 'error', e)
  }
 
  var req = (ssl ? https : http).request(options, function (res) {
    // Allow getting Response Headers from the XMLHTTPRequest object
    dfd.getResponseHeader = jqXHR.getResponseHeader = function (header) {
      return res.headers[header.toLowerCase()]
    }
    res.on('data', function (d) {
      data += d
    })
    res.on('end', function () {
      jqXHR.responseText = data
      Iif (o.dataType === 'json' || o.dataType === 'jsonp') {
        // replace control characters
        try {
          data = JSON.parse(data.replace(/[\cA-\cZ]/gi, ''))
        } catch (e) {
          return errorHandler(e)
        }
      }
 
      var statusCode = res.statusCode
      var statusText = 'success'
 
      Iif (statusCode === 204 || options.method === 'HEAD') {
        statusText = 'nocontent'
      } else Iif (statusCode === 304) {
        statusText = 'notmodified'
      }
 
      // Determine if successful
      // (per https://github.com/jquery/jquery/blob/master/src/ajax.js#L679)
      var isSuccess = statusCode >= 200 && statusCode < 300 || statusCode === 304
        // Set readyState
      jqXHR.readyState = statusCode > 0 ? 4 : 0
      jqXHR.status = statusCode
 
      Eif (isSuccess) {
        // Set data for the fake xhr object
        jqXHR.statusText = statusText
 
        Eif (_.isFunction(o.success)) {
          o.success(data, statusText, jqXHR)
        }
        // success, statusText, jqXHR
        dfd.resolve(data, statusText, jqXHR)
      } else {
        // jqXHR, statusText, error
        // When an HTTP error occurs, errorThrown receives the textual portion of the
        // HTTP status, such as "Not Found" or "Internal Server Error."
        statusText = 'error'
        if (_.isFunction(o.error)) {
          o.error(jqXHR, statusText, http.STATUS_CODES[statusCode])
        }
        dfd.reject(jqXHR, statusText, http.STATUS_CODES[statusCode])
      }
    })
  })
 
  // ERROR
  req.on('error', errorHandler)
 
  // SET TIMEOUT
  if (o.timeout && o.timeout > 0) {
    req.on('socket', function (socket) {
      socket.setTimeout(o.timeout)
      socket.on('timeout', function () {
        req.abort()
 
        Iif (_.isFunction(o.error)) {
          o.error(jqXHR, 'timeout')
        }
 
        dfd.reject(jqXHR, 'timeout')
      })
    })
  }
 
  // SEND DATA
  if (o.method !== 'GET' && o.data) {
    req.write(o.data, 'utf-8')
  }
  req.end()
 
  // DEFERRED
  dfd.success = dfd.done
  dfd.error = dfd.fail
  return dfd
}