Call action and method form resolved route
@param request
@param response
@param callback
@returns {*}
762569
function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }
664974
function getHandler (method, trans, version) {
  return function (req, res, next) {
    res.setHeader('Allow', Object.values(allowedMethods).join(','));

    let service = req.params.__service;
    let id = req.params.__id;
    let action = req.params.__action;
    let path = '/' + service +
      (id? '/' + id : '') +
      (action? '/' + action : '');
    
    // guess whether id is an action?
    if (id && !action) {
      if (!(validator.isNumeric(id) || validator.isMongoId(id))) {
        action = id;
      }
    }
    service += (action? '.' + action : '');
    
    debug(`REST handler calling service \'${service}\'`);
    debug(` => cmd  \'${method}\'`);
    debug(` => path \'${path}\'`);
    debug(` => version \'${version}\'`);

    // The service success callback which sets res.data or calls next() with the error
    const callback = function (err, data) {
      debug(' => service response:', err, data);
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'post') {
        res.status(statusCodes.created);
      }

      return next();
    };

    trans.act({
      topic: `poplar.${service}`,
      cmd: method,
      path: path,
      version: version,
      headers: req.headers || {},
      query: req.query || {},
      body: req.body || {}
    }, callback);
  };
}
572395
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    /**
     * Parse the body of the request as a JSON object and return it.
     */
    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body ? JSON.parse(opts.body) : opts.body;
        },
    });

    /**
     * Return the raw body passed to request
     */
    Object.defineProperty(this, 'rawData', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}
636712
function(req, res, route) {
    req.on('data', function(data) {
      req.body = queryStringToJSON(data.toString());
      route.callback(req, res);
    });
  }
466591
function (request, response) {
    var path = url.parse(request.url, false).pathname;

    if (path === '/') {
      // A base request just prints out the current Imagine version
      response.writeHead(200, { 'content-type': 'application/json' });
      response.end(JSON.stringify({ version: '0.1.0' }));
    } else {
      // All other requests are passed to the handler
      new RequestHandler(request, response).handle();
    }
  }
689708
function getMethod(methodname) {
  if (controllers[methodname]) {
    return function(call, callback) {
      console.log(call);
      return controllers[methodname](call, callback);
    };
  } else {
    return function(call, callback) {
      // By default we print an empty response.
      callback(null, {});
    };
  }
}
1286401
function ajax(url, callback, data) {
  if (data) {
    var reqOptions = typeof url === 'string' ? { uri: url, body: data, json: true } : _extends({}, url, { body: data, json: true });
    _request2.default.post(reqOptions, function (err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  } else {
    (0, _request2.default)(url, function (err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  }
}
41440
function getRequest(path, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {
      method: 'get'
    };
  } else {
    options.method = 'get';
  }

  if (options.params) {
    var uri = url.parse(path, true);
    uri.query = _.merge({}, uri.query, options.params);
    path = url.format(uri);
    delete options.params;
  }

  sendRequest(path, options, callback);
}
1161358
function responseCallback(response, model, success) {
        // Add response to a hash that will eventually be returned through the promise
        responses[model.cid] = {
            success: success,
            response: response
          };
        // If we have reached the total of number of expected responses, then resolve or reject the promise
        if (responsesFailed + responsesSucceeded === numberOfSaves) {
          if (responsesFailed > 0) {
            // Rollback if any responses have failed
            if (options.rollback) {
              _.each(formModel.getTrackedModels(), function(model) {
                model.set(oldValues[model.cid]);
                if (responses[model.cid].success) {
                  model.save();
                }
              });
            }
            formModel.trigger('save-fail', responses);
            deferred.reject(responses);
          } else {
            formModel.trigger('save-success', responses);
            deferred.resolve(responses);
          }
        }
      }
1101866
function Request(method, url) {
  var self = this;
  Emitter.call(this);
  this._query = this._query || [];
  this.method = method;
  this.url = url;
  this.header = {};
  this._header = {};
  this.on('end', function(){
    var res = new Response(self);
    if ('HEAD' == method) res.text = null;
    self.callback(null, res);
  });
}
1199517
function(middlewares, response, callback) {
        var that = this;
        var middleware = middlewares.shift();
        if (!middleware) {
            return callback(null, response);
        }
        var middleware_callback = function(retVal) {
            /**
             * got an error
             * break middleware chain and callback
             */
            if (retVal && retVal instanceof Error) {
                return callback(retVal, response);
            }
            /**
             * got a response object
             * break middleware chain and bypass request
             */
            if (retVal && typeof retVal == 'object') {
                return callback(null, retVal);
            }
            that._callResponseMiddlewares(middlewares, response, callback);
        };
        try {
            middleware(response, middleware_callback);
        } catch (e) {
            callback(e, response);
        }
    }
576483
function requestHandler (method) {
  return function (req, res, next) {
    method.call(this, req, responseHandler(res, next));
  }.bind(this);
}
981379
function(routes, callback) {
    var newRoutes = {};

    // Add a route.
    newRoutes['/test'] = {
      callback: function(request, response) {
        response.send('Testing!');
      }
    };

    // Add another route.
    newRoutes['/test-altering'] = {
      callback: function(request, response) {
        response.send('Testing!');
      }
    };

    callback(null, newRoutes);
  }
549894
function(request, callback, response_middlewares) {
        var that = this;
        request.finalize(function(err, res) {
            if (err) callback(err, null);
            else that._callResponseMiddlewares(response_middlewares, res, callback);
        });
    }
679210
function (response) {
              var swagger = response.obj;
              self.resolveItem(swagger, item.root, resolutionTable, resolvedRefs, unresolvedRefs, item);
              processedCalls += 1;

              if (processedCalls === expectedCalls) {
                self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback);
              }
            }
931931
function(response, resolver, callbackSuccess, callbackError) {

            //xhr = xhr.target || xhr || {};
            var statusCode = xhrSuccessStatus[response.status] || response.status,
                statusType = Number(response.status.toString()[0]),
                promiseResponse;

            var data = response.response;
            var headers = corbel.utils.keysToLowerCase(response.headers);

            if (statusType <= 3 && !response.error) {

                if (response.response) {
                    data = request.parse(response.response, response.responseType, response.dataType);
                }

                if (callbackSuccess) {
                    callbackSuccess.call(this, data, statusCode, response.responseObject, headers);
                }

                promiseResponse = {
                    data: data,
                    status: statusCode,
                    headers: headers
                };

                promiseResponse[response.responseObjectType] = response.responseObject;

                resolver.resolve(promiseResponse);
            } else {

                var disconnected = response.error && response.status === 0;
                statusCode = disconnected ? 0 : statusCode;

                if (callbackError) {
                    callbackError.call(this, response.error, statusCode, response.responseObject, headers);
                }

                if (response.response) {
                    data = request.parse(response.response, response.responseType, response.dataType);
                }

                promiseResponse = {
                    data: data,
                    status: statusCode,
                    error: response.error,
                    headers: headers
                };

                promiseResponse[response.responseObjectType] = response.responseObject;

                resolver.reject(promiseResponse);
            }
        }
1204552
function(err, data, response) {

				// call the 'response' callback, if provided using 'node' style callback pattern
				if (options.complete) {
					options.complete.call(model, err, data, response, options);
				}

				// trigger any event listeners for "complete"
				model.trigger('complete', err, data, response, options);
			}