Socket
Socket
Sign inDemoInstall

mappersmith

Package Overview
Dependencies
Maintainers
3
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mappersmith - npm Package Compare versions

Comparing version 0.12.1 to 0.13.0

2

build/mappersmith-fixture.js
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.MappersmithFixture = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
/*!
* Mappersmith 0.12.1, Fixture support
* Mappersmith 0.13.0, Fixture support
* https://github.com/tulios/mappersmith

@@ -6,0 +6,0 @@ */

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Mappersmith = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*!
* Mappersmith 0.12.1
* Mappersmith 0.13.0
* https://github.com/tulios/mappersmith

@@ -158,2 +158,3 @@ */

if (this.successHandler) this.successHandler.apply(this, [stats, data]);
callback(data, stats);

@@ -201,2 +202,6 @@ }.bind(this);

setSuccessHandler: function(successHandler) {
this.successHandler = successHandler;
},
shouldEmulateHTTP: function(method) {

@@ -282,6 +287,11 @@ return !!(this.opts.emulateHTTP && /^(delete|put|patch)/i.test(method));

_jQueryAjax: function(config) {
if (config.withCredentials) {
delete config.withCredentials;
config = Utils.extend(config, {xhrFields: {withCredentials: true}});
}
jQuery.ajax(Utils.extend({url: this.url}, config)).
done(function(data, textStatus, xhr) {
var headers = Utils.parseResponseHeaders(xhr.getAllResponseHeaders());
this.successCallback(data, {responseHeaders: headers});
this.successCallback(data, {status: xhr.status, responseHeaders: headers});

@@ -363,2 +373,5 @@ }.bind(this)).

// IE sends 1223 instead of 204
if (status === 1223) status = 204;
try {

@@ -374,3 +387,7 @@ if (status >= 200 && status < 400) {

var responseHeaders = request.getAllResponseHeaders();
var extra = {responseHeaders: Utils.parseResponseHeaders(responseHeaders)};
var extra = {
status: status,
responseHeaders: Utils.parseResponseHeaders(responseHeaders)
};
this.successCallback(data, extra);

@@ -395,2 +412,6 @@

if (this.opts.withCredentials) {
request.withCredentials = true;
}
if (this.opts.configure) {

@@ -433,2 +454,3 @@ this.opts.configure(request);

this.globalErrorHandler = Utils.noop;
this.globalSuccessHandler = Utils.noop;
}

@@ -448,7 +470,6 @@

createContext: function() {
var errorAssigner = function(handler) {
this.globalErrorHandler = handler;
}.bind(this);
return {onError: errorAssigner};
return {
onSuccess: function(handler) { this.globalSuccessHandler = handler }.bind(this),
onError: function(handler) { this.globalErrorHandler = handler }.bind(this)
};
},

@@ -513,6 +534,6 @@

newGatewayRequest: function(descriptor) {
var rules = this.rules.
resolveRules: function(descriptor, resolvedUrl) {
return this.rules.
filter(function(rule) {
return rule.match === undefined || rule.match.test(descriptor.path)
return rule.match === undefined || rule.match.test(resolvedUrl)
}).

@@ -525,3 +546,5 @@ reduce(function(context, rule) {

}, {});
},
newGatewayRequest: function(descriptor) {
return function(params, callback, opts) {

@@ -532,2 +555,5 @@ if (typeof params === 'function') {

params = undefined;
} else if (callback && typeof callback !== 'function') {
opts = callback;
callback = Utils.noop;
}

@@ -539,10 +565,2 @@

opts = Utils.extend({}, opts, rules.gateway);
if (params && params.headers) {
opts.headers = Utils.extend(opts.headers, params.headers);
delete params['headers']
}
if (Utils.isObjEmpty(opts)) opts = undefined;
var host = this.resolveHost(descriptor.host);

@@ -556,2 +574,11 @@ var path = this.resolvePath(descriptor.path, params);

var fullUrl = host + path;
var rules = this.resolveRules(descriptor, fullUrl);
opts = Utils.extend({}, opts, rules.gateway);
if (params && params.headers) {
opts.headers = Utils.extend(opts.headers, params.headers);
delete params['headers']
}
if (Utils.isObjEmpty(opts)) opts = undefined;
var body = (params || {})[this.bodyAttr];

@@ -573,3 +600,5 @@

var gateway = new this.Gateway(gatewayOpts);
gateway.setSuccessHandler(this.globalSuccessHandler);
gateway.setErrorHandler(this.globalErrorHandler);
if (Env.USE_PROMISES) return gateway.promisify(callback);

@@ -634,34 +663,34 @@ return gateway.success(callback).call();

var options, name, src, copy, clone;
var target = arguments[0] || {};
var length = arguments.length;
var target = arguments[0] || {};
var length = arguments.length;
// Handle case when target is a string or something
if (typeof target !== 'object') target = {};
// Handle case when target is a string or something
if (typeof target !== 'object') target = {};
for (var i = 1; i < length; i++) {
// Only deal with non-null/undefined values
for (var i = 1; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) === null) continue;
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) continue;
// Prevent never-ending loop
if (target === copy) continue;
// Recurse if we're merging plain objects or arrays
if (copy && isObject(copy)) {
clone = src && isObject(src) ? src : {};
// Never move original objects, clone them
target[name] = this.extend(clone, copy);
// Recurse if we're merging plain objects or arrays
if (copy && isObject(copy)) {
clone = src && isObject(src) ? src : {};
// Never move original objects, clone them
target[name] = this.extend(clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
return target;
return target;
},

@@ -668,0 +697,0 @@

!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.Mappersmith=f()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){/*!
* Mappersmith 0.12.1
* Mappersmith 0.13.0
* https://github.com/tulios/mappersmith
*/
module.exports={Env:require("./src/env"),Utils:require("./src/utils"),Gateway:require("./src/gateway"),Mapper:require("./src/mapper"),VanillaGateway:require("./src/gateway/vanilla-gateway"),JQueryGateway:require("./src/gateway/jquery-gateway"),forge:require("./src/forge"),createGateway:require("./src/create-gateway")}},{"./src/create-gateway":2,"./src/env":3,"./src/forge":4,"./src/gateway":5,"./src/gateway/jquery-gateway":6,"./src/gateway/vanilla-gateway":7,"./src/mapper":8,"./src/utils":9}],2:[function(require,module,exports){var Utils=require("./utils"),Gateway=require("./gateway");module.exports=function(methods){var newGateway=function(){return this.init&&this.init(),Gateway.apply(this,arguments)};return newGateway.prototype=Utils.extend({},Gateway.prototype,methods),newGateway}},{"./gateway":5,"./utils":9}],3:[function(require,module,exports){module.exports={USE_FIXTURES:!1,USE_PROMISES:!1,Fixture:null,Promise:"function"==typeof Promise?Promise:null}},{}],4:[function(require,module,exports){var Mapper=require("./mapper"),VanillaGateway=require("./gateway/vanilla-gateway");module.exports=function(manifest,gateway,bodyAttr){return new Mapper(manifest,gateway||VanillaGateway,bodyAttr||"body").build()}},{"./gateway/vanilla-gateway":7,"./mapper":8}],5:[function(require,module,exports){var Env=require("./env"),Utils=require("./utils"),Promise=require("./env").Promise,Gateway=function(args){this.url=args.url,this.host=args.host,this.path=args.path,this.params=args.params||{},this.method=args.method,this.body=args.body,this.processor=args.processor,this.opts=args.opts||{},this.timeStart=null,this.timeEnd=null,this.timeElapsed=null,this.success(Utils.noop),this.fail(Utils.noop),this.complete(Utils.noop)};Gateway.prototype={call:function(){return this.timeStart=Utils.performanceNow(),Env.USE_FIXTURES&&Env.Fixture?this.callWithFixture():this[this.method].apply(this,arguments),this},callWithFixture:function(){var resource=this.getRequestedResource(),entry=Env.Fixture.lookup(this.method,resource);if(!entry)throw new Utils.Exception("No fixture provided for "+JSON.stringify(resource));setTimeout(function(){entry.isSuccess()?this.successCallback(entry.callWith(resource)):this.failCallback(entry.callWith(resource))}.bind(this),1)},promisify:function(thenCallback){var promise=new Promise(function(resolve,reject){this.success(function(data,stats){resolve({data:data,stats:stats})}),this.fail(function(){for(var args=[],i=0;i<arguments.length;i++)args.push(arguments[i]);var request=args.shift();reject({request:request,err:args})}),this.call()}.bind(this));return void 0!==thenCallback?promise.then(thenCallback):promise},success:function(callback){return this.successCallback=function(data,extraStats){this.timeEnd=Utils.performanceNow(),this.timeElapsed=this.timeEnd-this.timeStart,this.processor&&(data=this.processor(data));var requestedResource=this.getRequestedResource(),stats=Utils.extend({timeElapsed:this.timeElapsed,timeElapsedHumanized:Utils.humanizeTimeElapsed(this.timeElapsed)},requestedResource,extraStats);callback(data,stats)}.bind(this),this},fail:function(callback){return this.failCallback=function(errorObj){errorObj=errorObj||{status:400,args:[]};var gatewayArgs=Array.prototype.slice.call(errorObj.args),status=errorObj.status,resource=this.getRequestedResource(),errorResource=Utils.extend({status:status},resource),args=[errorResource].concat(gatewayArgs),proceed=!0;this.errorHandler&&(proceed=!(this.errorHandler.apply(this,args)===!0)),proceed&&callback.apply(this,args)}.bind(this),this},complete:function(callback){return this.completeCallback=callback,this},getRequestedResource:function(){return{url:this.url,host:this.host,path:this.path,params:this.params,headers:this.opts.headers}},setErrorHandler:function(errorHandler){this.errorHandler=errorHandler},shouldEmulateHTTP:function(method){return!(!this.opts.emulateHTTP||!/^(delete|put|patch)/i.test(method))},get:function(){throw new Utils.Exception("Gateway#get not implemented")},post:function(){throw new Utils.Exception("Gateway#post not implemented")},put:function(){throw new Utils.Exception("Gateway#put not implemented")},delete:function(){throw new Utils.Exception("Gateway#delete not implemented")},patch:function(){throw new Utils.Exception("Gateway#patch not implemented")}},module.exports=Gateway},{"./env":3,"./utils":9}],6:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),JQueryGateway=CreateGateway({init:function(){if(void 0===window.jQuery)throw new Utils.Exception("JQueryGateway requires jQuery but it was not found! Change the gateway implementation or add jQuery on the page")},get:function(){return this._jQueryAjax(this.opts),this},post:function(){return this._performRequest("POST")},put:function(){return this._performRequest("PUT")},patch:function(){return this._performRequest("PATCH")},delete:function(){return this._performRequest("DELETE")},_performRequest:function(method){var requestMethod=method;this.shouldEmulateHTTP(method)&&(requestMethod="POST",this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),this.opts.headers=Utils.extend({"X-HTTP-Method-Override":method},this.opts.headers));var defaults={type:requestMethod,data:Utils.params(this.body)};return this._jQueryAjax(Utils.extend(defaults,this.opts)),this},_jQueryAjax:function(config){jQuery.ajax(Utils.extend({url:this.url},config)).done(function(data,textStatus,xhr){var headers=Utils.parseResponseHeaders(xhr.getAllResponseHeaders());this.successCallback(data,{responseHeaders:headers})}.bind(this)).fail(function(jqXHR){this.failCallback({status:jqXHR.status,args:arguments})}.bind(this)).always(function(){this.completeCallback.apply(this,arguments)}.bind(this))}});module.exports=JQueryGateway},{"../create-gateway":2,"../utils":9}],7:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),VanillaGateway=CreateGateway({get:function(){var request=new XMLHttpRequest;this._configureCallbacks(request),request.open("GET",this.url,!0),this._setHeaders(request),request.send()},post:function(){this._performRequest("POST")},put:function(){this._performRequest("PUT")},patch:function(){this._performRequest("PATCH")},delete:function(){this._performRequest("DELETE")},_performRequest:function(method){var emulateHTTP=this.shouldEmulateHTTP(method),requestMethod=method,request=new XMLHttpRequest;this._configureCallbacks(request),emulateHTTP&&(this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),requestMethod="POST"),request.open(requestMethod,this.url,!0),emulateHTTP&&request.setRequestHeader("X-HTTP-Method-Override",method),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),this._setHeaders(request);var args=[];void 0!==this.body&&args.push(Utils.params(this.body)),request.send.apply(request,args)},_configureCallbacks:function(request){request.onload=function(){var data=null,status=request.status;try{if(status>=200&&400>status){data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText;var responseHeaders=request.getAllResponseHeaders(),extra={responseHeaders:Utils.parseResponseHeaders(responseHeaders)};this.successCallback(data,extra)}else this.failCallback({status:status,args:[request]})}catch(e){this.failCallback({status:status,args:[request]})}finally{this.completeCallback(data,request)}}.bind(this),request.onerror=function(){this.failCallback({status:400,args:[arguments]}),this.completeCallback.apply(this,arguments)}.bind(this),this.opts.configure&&this.opts.configure(request)},_setHeaders:function(request){var headers=Utils.extend({},this.opts.headers);Object.keys(headers).forEach(function(headerName){request.setRequestHeader(headerName,headers[headerName])})},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":9}],8:[function(require,module,exports){var Utils=require("./utils"),Env=require("./env"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.rules=this.manifest.rules||[],this.Gateway=Gateway,this.bodyAttr=bodyAttr,this.globalErrorHandler=Utils.noop};Mapper.prototype={build:function(){return Object.keys(this.manifest.resources||{}).map(function(name){return this.buildResource(name)}.bind(this)).reduce(function(context,resource){return context[resource.name]=resource.methods,context},this.createContext())},createContext:function(){var errorAssigner=function(handler){this.globalErrorHandler=handler}.bind(this);return{onError:errorAssigner}},buildResource:function(resourceName){var methods=this.manifest.resources[resourceName];return Object.keys(methods).reduce(function(context,methodName){var descriptor=methods[methodName];if("string"==typeof descriptor){var compactDefinitionMethod=descriptor.match(/^(get|post|delete|put|patch):(.*)/);descriptor=null!=compactDefinitionMethod?{method:compactDefinitionMethod[1],path:compactDefinitionMethod[2]}:{method:"get",path:descriptor}}return descriptor.method=(descriptor.method||"get").toLowerCase(),context.methods[methodName]=this.newGatewayRequest(descriptor),context}.bind(this),{name:resourceName,methods:{}})},resolvePath:function(pathDefinition,urlParams){var params=Utils.extend({},urlParams),resolvedPath=pathDefinition;delete params[this.bodyAttr],delete params.headers,Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(resolvedPath)&&(resolvedPath=resolvedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),resolvedPath+paramsString},resolveHost:function(value){return("undefined"==typeof value||null===value)&&(value=this.manifest.host),value===!1&&(value=""),value.replace(/\/$/,"")},newGatewayRequest:function(descriptor){var rules=this.rules.filter(function(rule){return void 0===rule.match||rule.match.test(descriptor.path)}).reduce(function(context,rule){var mergedGateway=Utils.extend(context.gateway,rule.values.gateway);return context=Utils.extend(context,rule.values),context.gateway=mergedGateway,context},{});return function(params,callback,opts){"function"==typeof params&&(opts=callback,callback=params,params=void 0),descriptor.params&&(params=Utils.extend({},descriptor.params,params)),opts=Utils.extend({},opts,rules.gateway),params&&params.headers&&(opts.headers=Utils.extend(opts.headers,params.headers),delete params.headers),Utils.isObjEmpty(opts)&&(opts=void 0);var host=this.resolveHost(descriptor.host),path=this.resolvePath(descriptor.path,params);""!==host&&(path=/^\//.test(path)?path:"/"+path);var fullUrl=host+path,body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:fullUrl,host:host,path:path,params:params,body:body,method:descriptor.method,processor:descriptor.processor||rules.processor,opts:opts}),gateway=new this.Gateway(gatewayOpts);return gateway.setErrorHandler(this.globalErrorHandler),Env.USE_PROMISES?gateway.promisify(callback):gateway.success(callback).call()}.bind(this)}},module.exports=Mapper},{"./env":3,"./utils":9}],9:[function(require,module,exports){function hasProcessHrtime(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime}function isObject(value){return"[object Object]"===Object.prototype.toString.call(value)}"undefined"!=typeof window&&null!==window&&(window.performance=window.performance||{},performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process;try{_process=eval("process")}catch(e){}var getNanoSeconds,loadTime;hasProcessHrtime()&&(getNanoSeconds=function(){var hr=_process.hrtime();return 1e9*hr[0]+hr[1]},loadTime=getNanoSeconds());var Utils={r20:/%20/g,noop:function(){},isObjEmpty:function(obj){for(var key in obj)if(obj.hasOwnProperty(key))return!1;return!0},extend:function(out){var options,name,src,copy,clone,target=arguments[0]||{},length=arguments.length;"object"!=typeof target&&(target={});for(var i=1;length>i;i++)if(null!==(options=arguments[i]))for(name in options)src=target[name],copy=options[name],target!==copy&&(copy&&isObject(copy)?(clone=src&&isObject(src)?src:{},target[name]=this.extend(clone,copy)):void 0!==copy&&(target[name]=copy));return target},params:function(entry){if("object"!=typeof entry)return entry;var validKeys=function(entry){return Object.keys(entry).filter(function(key){return void 0!==entry[key]&&null!==entry[key]})},buildRecursive=function(key,value,suffix){suffix=suffix||"";var isArray=Array.isArray(value),isObject="object"==typeof value;return isArray||isObject?isArray?value.map(function(v){return buildRecursive(key,v,suffix+"[]")}).join("&"):validKeys(value).map(function(k){return buildRecursive(key,value[k],suffix+"["+k+"]")}).join("&"):encodeURIComponent(key+suffix)+"="+encodeURIComponent(value)};return validKeys(entry).map(function(key){return buildRecursive(key,entry[key])}).join("&").replace(Utils.r20,"+")},parseResponseHeaders:function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i<headerPairs.length;i++){var headerPair=headerPairs[i],index=headerPair.indexOf(": ");if(index>0){var key=headerPair.substring(0,index).toLowerCase(),val=headerPair.substring(index+2);headers[key]=val}}return headers},performanceNow:function(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()},humanizeTimeElapsed:function(timeElapsed){return timeElapsed>=1e3?(timeElapsed/1e3).toFixed(2)+" s":timeElapsed.toFixed(2)+" ms"},Exception:function(message){var err=new Error("[Mappersmith] "+message);this.message=err.message,this.stack=err.stack,this.toString=function(){return this.message}}};module.exports=Utils},{}]},{},[1])(1)});
module.exports={Env:require("./src/env"),Utils:require("./src/utils"),Gateway:require("./src/gateway"),Mapper:require("./src/mapper"),VanillaGateway:require("./src/gateway/vanilla-gateway"),JQueryGateway:require("./src/gateway/jquery-gateway"),forge:require("./src/forge"),createGateway:require("./src/create-gateway")}},{"./src/create-gateway":2,"./src/env":3,"./src/forge":4,"./src/gateway":5,"./src/gateway/jquery-gateway":6,"./src/gateway/vanilla-gateway":7,"./src/mapper":8,"./src/utils":9}],2:[function(require,module,exports){var Utils=require("./utils"),Gateway=require("./gateway");module.exports=function(methods){var newGateway=function(){return this.init&&this.init(),Gateway.apply(this,arguments)};return newGateway.prototype=Utils.extend({},Gateway.prototype,methods),newGateway}},{"./gateway":5,"./utils":9}],3:[function(require,module,exports){module.exports={USE_FIXTURES:!1,USE_PROMISES:!1,Fixture:null,Promise:"function"==typeof Promise?Promise:null}},{}],4:[function(require,module,exports){var Mapper=require("./mapper"),VanillaGateway=require("./gateway/vanilla-gateway");module.exports=function(manifest,gateway,bodyAttr){return new Mapper(manifest,gateway||VanillaGateway,bodyAttr||"body").build()}},{"./gateway/vanilla-gateway":7,"./mapper":8}],5:[function(require,module,exports){var Env=require("./env"),Utils=require("./utils"),Promise=require("./env").Promise,Gateway=function(args){this.url=args.url,this.host=args.host,this.path=args.path,this.params=args.params||{},this.method=args.method,this.body=args.body,this.processor=args.processor,this.opts=args.opts||{},this.timeStart=null,this.timeEnd=null,this.timeElapsed=null,this.success(Utils.noop),this.fail(Utils.noop),this.complete(Utils.noop)};Gateway.prototype={call:function(){return this.timeStart=Utils.performanceNow(),Env.USE_FIXTURES&&Env.Fixture?this.callWithFixture():this[this.method].apply(this,arguments),this},callWithFixture:function(){var resource=this.getRequestedResource(),entry=Env.Fixture.lookup(this.method,resource);if(!entry)throw new Utils.Exception("No fixture provided for "+JSON.stringify(resource));setTimeout(function(){entry.isSuccess()?this.successCallback(entry.callWith(resource)):this.failCallback(entry.callWith(resource))}.bind(this),1)},promisify:function(thenCallback){var promise=new Promise(function(resolve,reject){this.success(function(data,stats){resolve({data:data,stats:stats})}),this.fail(function(){for(var args=[],i=0;i<arguments.length;i++)args.push(arguments[i]);var request=args.shift();reject({request:request,err:args})}),this.call()}.bind(this));return void 0!==thenCallback?promise.then(thenCallback):promise},success:function(callback){return this.successCallback=function(data,extraStats){this.timeEnd=Utils.performanceNow(),this.timeElapsed=this.timeEnd-this.timeStart,this.processor&&(data=this.processor(data));var requestedResource=this.getRequestedResource(),stats=Utils.extend({timeElapsed:this.timeElapsed,timeElapsedHumanized:Utils.humanizeTimeElapsed(this.timeElapsed)},requestedResource,extraStats);this.successHandler&&this.successHandler.apply(this,[stats,data]),callback(data,stats)}.bind(this),this},fail:function(callback){return this.failCallback=function(errorObj){errorObj=errorObj||{status:400,args:[]};var gatewayArgs=Array.prototype.slice.call(errorObj.args),status=errorObj.status,resource=this.getRequestedResource(),errorResource=Utils.extend({status:status},resource),args=[errorResource].concat(gatewayArgs),proceed=!0;this.errorHandler&&(proceed=!(this.errorHandler.apply(this,args)===!0)),proceed&&callback.apply(this,args)}.bind(this),this},complete:function(callback){return this.completeCallback=callback,this},getRequestedResource:function(){return{url:this.url,host:this.host,path:this.path,params:this.params,headers:this.opts.headers}},setErrorHandler:function(errorHandler){this.errorHandler=errorHandler},setSuccessHandler:function(successHandler){this.successHandler=successHandler},shouldEmulateHTTP:function(method){return!(!this.opts.emulateHTTP||!/^(delete|put|patch)/i.test(method))},get:function(){throw new Utils.Exception("Gateway#get not implemented")},post:function(){throw new Utils.Exception("Gateway#post not implemented")},put:function(){throw new Utils.Exception("Gateway#put not implemented")},delete:function(){throw new Utils.Exception("Gateway#delete not implemented")},patch:function(){throw new Utils.Exception("Gateway#patch not implemented")}},module.exports=Gateway},{"./env":3,"./utils":9}],6:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),JQueryGateway=CreateGateway({init:function(){if(void 0===window.jQuery)throw new Utils.Exception("JQueryGateway requires jQuery but it was not found! Change the gateway implementation or add jQuery on the page")},get:function(){return this._jQueryAjax(this.opts),this},post:function(){return this._performRequest("POST")},put:function(){return this._performRequest("PUT")},patch:function(){return this._performRequest("PATCH")},delete:function(){return this._performRequest("DELETE")},_performRequest:function(method){var requestMethod=method;this.shouldEmulateHTTP(method)&&(requestMethod="POST",this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),this.opts.headers=Utils.extend({"X-HTTP-Method-Override":method},this.opts.headers));var defaults={type:requestMethod,data:Utils.params(this.body)};return this._jQueryAjax(Utils.extend(defaults,this.opts)),this},_jQueryAjax:function(config){config.withCredentials&&(delete config.withCredentials,config=Utils.extend(config,{xhrFields:{withCredentials:!0}})),jQuery.ajax(Utils.extend({url:this.url},config)).done(function(data,textStatus,xhr){var headers=Utils.parseResponseHeaders(xhr.getAllResponseHeaders());this.successCallback(data,{status:xhr.status,responseHeaders:headers})}.bind(this)).fail(function(jqXHR){this.failCallback({status:jqXHR.status,args:arguments})}.bind(this)).always(function(){this.completeCallback.apply(this,arguments)}.bind(this))}});module.exports=JQueryGateway},{"../create-gateway":2,"../utils":9}],7:[function(require,module,exports){var Utils=require("../utils"),CreateGateway=require("../create-gateway"),VanillaGateway=CreateGateway({get:function(){var request=new XMLHttpRequest;this._configureCallbacks(request),request.open("GET",this.url,!0),this._setHeaders(request),request.send()},post:function(){this._performRequest("POST")},put:function(){this._performRequest("PUT")},patch:function(){this._performRequest("PATCH")},delete:function(){this._performRequest("DELETE")},_performRequest:function(method){var emulateHTTP=this.shouldEmulateHTTP(method),requestMethod=method,request=new XMLHttpRequest;this._configureCallbacks(request),emulateHTTP&&(this.body=this.body||{},"object"==typeof this.body&&(this.body._method=method),requestMethod="POST"),request.open(requestMethod,this.url,!0),emulateHTTP&&request.setRequestHeader("X-HTTP-Method-Override",method),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),this._setHeaders(request);var args=[];void 0!==this.body&&args.push(Utils.params(this.body)),request.send.apply(request,args)},_configureCallbacks:function(request){request.onload=function(){var data=null,status=request.status;1223===status&&(status=204);try{if(status>=200&&400>status){data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText;var responseHeaders=request.getAllResponseHeaders(),extra={status:status,responseHeaders:Utils.parseResponseHeaders(responseHeaders)};this.successCallback(data,extra)}else this.failCallback({status:status,args:[request]})}catch(e){this.failCallback({status:status,args:[request]})}finally{this.completeCallback(data,request)}}.bind(this),request.onerror=function(){this.failCallback({status:400,args:[arguments]}),this.completeCallback.apply(this,arguments)}.bind(this),this.opts.withCredentials&&(request.withCredentials=!0),this.opts.configure&&this.opts.configure(request)},_setHeaders:function(request){var headers=Utils.extend({},this.opts.headers);Object.keys(headers).forEach(function(headerName){request.setRequestHeader(headerName,headers[headerName])})},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":9}],8:[function(require,module,exports){var Utils=require("./utils"),Env=require("./env"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.rules=this.manifest.rules||[],this.Gateway=Gateway,this.bodyAttr=bodyAttr,this.globalErrorHandler=Utils.noop,this.globalSuccessHandler=Utils.noop};Mapper.prototype={build:function(){return Object.keys(this.manifest.resources||{}).map(function(name){return this.buildResource(name)}.bind(this)).reduce(function(context,resource){return context[resource.name]=resource.methods,context},this.createContext())},createContext:function(){return{onSuccess:function(handler){this.globalSuccessHandler=handler}.bind(this),onError:function(handler){this.globalErrorHandler=handler}.bind(this)}},buildResource:function(resourceName){var methods=this.manifest.resources[resourceName];return Object.keys(methods).reduce(function(context,methodName){var descriptor=methods[methodName];if("string"==typeof descriptor){var compactDefinitionMethod=descriptor.match(/^(get|post|delete|put|patch):(.*)/);descriptor=null!=compactDefinitionMethod?{method:compactDefinitionMethod[1],path:compactDefinitionMethod[2]}:{method:"get",path:descriptor}}return descriptor.method=(descriptor.method||"get").toLowerCase(),context.methods[methodName]=this.newGatewayRequest(descriptor),context}.bind(this),{name:resourceName,methods:{}})},resolvePath:function(pathDefinition,urlParams){var params=Utils.extend({},urlParams),resolvedPath=pathDefinition;delete params[this.bodyAttr],delete params.headers,Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(resolvedPath)&&(resolvedPath=resolvedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),resolvedPath+paramsString},resolveHost:function(value){return("undefined"==typeof value||null===value)&&(value=this.manifest.host),value===!1&&(value=""),value.replace(/\/$/,"")},resolveRules:function(descriptor,resolvedUrl){return this.rules.filter(function(rule){return void 0===rule.match||rule.match.test(resolvedUrl)}).reduce(function(context,rule){var mergedGateway=Utils.extend(context.gateway,rule.values.gateway);return context=Utils.extend(context,rule.values),context.gateway=mergedGateway,context},{})},newGatewayRequest:function(descriptor){return function(params,callback,opts){"function"==typeof params?(opts=callback,callback=params,params=void 0):callback&&"function"!=typeof callback&&(opts=callback,callback=Utils.noop),descriptor.params&&(params=Utils.extend({},descriptor.params,params));var host=this.resolveHost(descriptor.host),path=this.resolvePath(descriptor.path,params);""!==host&&(path=/^\//.test(path)?path:"/"+path);var fullUrl=host+path,rules=this.resolveRules(descriptor,fullUrl);opts=Utils.extend({},opts,rules.gateway),params&&params.headers&&(opts.headers=Utils.extend(opts.headers,params.headers),delete params.headers),Utils.isObjEmpty(opts)&&(opts=void 0);var body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:fullUrl,host:host,path:path,params:params,body:body,method:descriptor.method,processor:descriptor.processor||rules.processor,opts:opts}),gateway=new this.Gateway(gatewayOpts);return gateway.setSuccessHandler(this.globalSuccessHandler),gateway.setErrorHandler(this.globalErrorHandler),Env.USE_PROMISES?gateway.promisify(callback):gateway.success(callback).call()}.bind(this)}},module.exports=Mapper},{"./env":3,"./utils":9}],9:[function(require,module,exports){function hasProcessHrtime(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime}function isObject(value){return"[object Object]"===Object.prototype.toString.call(value)}"undefined"!=typeof window&&null!==window&&(window.performance=window.performance||{},performance.now=function(){return performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()}}());var _process;try{_process=eval("process")}catch(e){}var getNanoSeconds,loadTime;hasProcessHrtime()&&(getNanoSeconds=function(){var hr=_process.hrtime();return 1e9*hr[0]+hr[1]},loadTime=getNanoSeconds());var Utils={r20:/%20/g,noop:function(){},isObjEmpty:function(obj){for(var key in obj)if(obj.hasOwnProperty(key))return!1;return!0},extend:function(out){var options,name,src,copy,clone,target=arguments[0]||{},length=arguments.length;"object"!=typeof target&&(target={});for(var i=1;length>i;i++)if(null!==(options=arguments[i]))for(name in options)src=target[name],copy=options[name],target!==copy&&(copy&&isObject(copy)?(clone=src&&isObject(src)?src:{},target[name]=this.extend(clone,copy)):void 0!==copy&&(target[name]=copy));return target},params:function(entry){if("object"!=typeof entry)return entry;var validKeys=function(entry){return Object.keys(entry).filter(function(key){return void 0!==entry[key]&&null!==entry[key]})},buildRecursive=function(key,value,suffix){suffix=suffix||"";var isArray=Array.isArray(value),isObject="object"==typeof value;return isArray||isObject?isArray?value.map(function(v){return buildRecursive(key,v,suffix+"[]")}).join("&"):validKeys(value).map(function(k){return buildRecursive(key,value[k],suffix+"["+k+"]")}).join("&"):encodeURIComponent(key+suffix)+"="+encodeURIComponent(value)};return validKeys(entry).map(function(key){return buildRecursive(key,entry[key])}).join("&").replace(Utils.r20,"+")},parseResponseHeaders:function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i<headerPairs.length;i++){var headerPair=headerPairs[i],index=headerPair.indexOf(": ");if(index>0){var key=headerPair.substring(0,index).toLowerCase(),val=headerPair.substring(index+2);headers[key]=val}}return headers},performanceNow:function(){return hasProcessHrtime()?(getNanoSeconds()-loadTime)/1e6:performance.now()},humanizeTimeElapsed:function(timeElapsed){return timeElapsed>=1e3?(timeElapsed/1e3).toFixed(2)+" s":timeElapsed.toFixed(2)+" ms"},Exception:function(message){var err=new Error("[Mappersmith] "+message);this.message=err.message,this.stack=err.stack,this.toString=function(){return this.message}}};module.exports=Utils},{}]},{},[1])(1)});
# Changelog
## 0.13.0
- Included status code for success calls
- `withCredentials` option for `VanillaGateway` and `JQueryGateway`
- Method to configure a global success handler per client
- bugfix: rules matcher now uses full URL instead of descriptor path
## 0.12.1

@@ -4,0 +11,0 @@

@@ -12,2 +12,3 @@ module.exports = function(config) {

'karma-browserify',
'karma-sourcemap-loader',
'karma-firefox-launcher',

@@ -39,4 +40,4 @@ 'karma-phantomjs2-launcher',

preprocessors: {
'index.js': ['browserify'],
'test/*.js': ['browserify']
'index.js': ['browserify', 'sourcemap'],
'test/*.js': ['browserify', 'sourcemap']
},

@@ -43,0 +44,0 @@

{
"name": "mappersmith",
"version": "0.12.1",
"version": "0.13.0",
"description": "It is a lightweight, isomorphic, dependency-free, rest client mapper for javascript",

@@ -40,9 +40,9 @@ "author": "Tulio Ornelas <ornelas.tulio@gmail.com>",

"aliasify": "^1.7.2",
"browserify": "^9.0.8",
"browserify-shim": "^3.8.10",
"browserify-versionify": "^1.0.4",
"browserify": "^13.0.0",
"browserify-shim": "^3.8.12",
"browserify-versionify": "^1.0.6",
"chai": "^1.10.0",
"jquery": "^2.1.4",
"karma": "^0.13.2",
"karma-browserify": "^4.2.1",
"karma": "^0.13.21",
"karma-browserify": "^5.0.1",
"karma-chai": "^0.1.0",

@@ -55,6 +55,7 @@ "karma-chrome-launcher": "^0.2.0",

"karma-sinon-chai": "^0.3.2",
"karma-sourcemap-loader": "^0.3.7",
"mocha": "^2.0.1",
"nock": "^0.58.0",
"phantomjs": "^1.9.17",
"promise": "^7.0.3",
"promise": "^7.1.1",
"rewire": "^2.3.0",

@@ -65,3 +66,4 @@ "rewireify": "0.0.13",

"sinon-chai": "^2.6.0",
"uglify-js": "^2.4.20"
"uglify-js": "^2.4.20",
"watchify": "^3.7.0"
},

@@ -68,0 +70,0 @@ "browserify": {

@@ -101,3 +101,3 @@ [![npm version](https://badge.fury.io/js/mappersmith.svg)](http://badge.fury.io/js/mappersmith)

### Success callback arguments
### <a name="success-callback-arguments"></a> Success callback arguments

@@ -117,2 +117,3 @@ The success callback will receive two arguments: the _first one_ will be `data`, returned by your API; and the _second one_ will be a `stats` object. The stats object hold information of the request, like the elapsed time between your call and callback execution.

headers: {Authorization: 'token 123'},
status: 200,
responseHeaders: {'content-type': 'application/json'}

@@ -126,2 +127,4 @@ timeElapsed: 6.745000369846821,

It's possible to assign a global success handler, take a look in a [section below](#global-success-handler)
### Fail callback arguments

@@ -140,3 +143,3 @@

It's possible to assign a global error handler, take a look in a [section below](#global-error-handling)
It's possible to assign a global error handler, take a look in a [section below](#global-error-handler)

@@ -347,7 +350,22 @@ ### Parameters

### <a name="global-error-handling"></a> Global error handling
### <a name="global-success-handler"></a> Global success handler
It's possible to assign a different global error handling for each generated client (every call to `forge` generates a new client), this is useful to remove repetition regarding authorization, content not found and so on. This error handler will be called for every error in any resource available in the client.
Sometimes you want to inspect all your requests for metrics, statistics or to notify activity. This handler will be called for every success response in any resource available to the client.
```javascript
Client.onSuccess(function(stats, data) {
console.log(data) // {data: 'my-data'}
console.log(stats.status) // 201
console.log(stats.url) // 'http://my.api.com/v1/books.json?language=en'
console.log(stats.params) // {language: 'en'}
});
```
Check the section [success callback arguments](#success-callback-arguments) for more information about the other attributes in stats.
### <a name="global-error-handler"></a> Global error handler
It's possible to assign a different global error handling for each generated client (every call to `forge` generates a new client), this is useful to remove repetition regarding authorization, content not found and so on. This error handler will be called for every error in any resource available to the client.
```javascript
Client.onError(function(request, err) {

@@ -509,2 +527,4 @@ console.log(request.url) // 'http://my.api.com/v1/books/3.json'

- withCredentials: Configure the property with same name
### JQueryGateway

@@ -528,2 +548,4 @@

- withCredentials: Configure the property with same name
### NodeVanillaGateway

@@ -530,0 +552,0 @@

@@ -106,2 +106,3 @@ var Env = require('./env');

if (this.successHandler) this.successHandler.apply(this, [stats, data]);
callback(data, stats);

@@ -149,2 +150,6 @@ }.bind(this);

setSuccessHandler: function(successHandler) {
this.successHandler = successHandler;
},
shouldEmulateHTTP: function(method) {

@@ -151,0 +156,0 @@ return !!(this.opts.emulateHTTP && /^(delete|put|patch)/i.test(method));

@@ -52,6 +52,11 @@ var Utils = require('../utils');

_jQueryAjax: function(config) {
if (config.withCredentials) {
delete config.withCredentials;
config = Utils.extend(config, {xhrFields: {withCredentials: true}});
}
jQuery.ajax(Utils.extend({url: this.url}, config)).
done(function(data, textStatus, xhr) {
var headers = Utils.parseResponseHeaders(xhr.getAllResponseHeaders());
this.successCallback(data, {responseHeaders: headers});
this.successCallback(data, {status: xhr.status, responseHeaders: headers});

@@ -58,0 +63,0 @@ }.bind(this)).

@@ -54,3 +54,3 @@ var Utils = require('../utils');

if (this.isContentTypeJSON(response)) data = JSON.parse(data);
this.successCallback(data, {responseHeaders: response.headers});
this.successCallback(data, {status: status, responseHeaders: response.headers});

@@ -57,0 +57,0 @@ } else {

@@ -60,2 +60,5 @@ var Utils = require('../utils');

// IE sends 1223 instead of 204
if (status === 1223) status = 204;
try {

@@ -71,3 +74,7 @@ if (status >= 200 && status < 400) {

var responseHeaders = request.getAllResponseHeaders();
var extra = {responseHeaders: Utils.parseResponseHeaders(responseHeaders)};
var extra = {
status: status,
responseHeaders: Utils.parseResponseHeaders(responseHeaders)
};
this.successCallback(data, extra);

@@ -92,2 +99,6 @@

if (this.opts.withCredentials) {
request.withCredentials = true;
}
if (this.opts.configure) {

@@ -94,0 +105,0 @@ this.opts.configure(request);

@@ -17,2 +17,3 @@ var Utils = require('./utils');

this.globalErrorHandler = Utils.noop;
this.globalSuccessHandler = Utils.noop;
}

@@ -32,7 +33,6 @@

createContext: function() {
var errorAssigner = function(handler) {
this.globalErrorHandler = handler;
}.bind(this);
return {onError: errorAssigner};
return {
onSuccess: function(handler) { this.globalSuccessHandler = handler }.bind(this),
onError: function(handler) { this.globalErrorHandler = handler }.bind(this)
};
},

@@ -97,6 +97,6 @@

newGatewayRequest: function(descriptor) {
var rules = this.rules.
resolveRules: function(descriptor, resolvedUrl) {
return this.rules.
filter(function(rule) {
return rule.match === undefined || rule.match.test(descriptor.path)
return rule.match === undefined || rule.match.test(resolvedUrl)
}).

@@ -109,3 +109,5 @@ reduce(function(context, rule) {

}, {});
},
newGatewayRequest: function(descriptor) {
return function(params, callback, opts) {

@@ -125,10 +127,2 @@ if (typeof params === 'function') {

opts = Utils.extend({}, opts, rules.gateway);
if (params && params.headers) {
opts.headers = Utils.extend(opts.headers, params.headers);
delete params['headers']
}
if (Utils.isObjEmpty(opts)) opts = undefined;
var host = this.resolveHost(descriptor.host);

@@ -142,2 +136,11 @@ var path = this.resolvePath(descriptor.path, params);

var fullUrl = host + path;
var rules = this.resolveRules(descriptor, fullUrl);
opts = Utils.extend({}, opts, rules.gateway);
if (params && params.headers) {
opts.headers = Utils.extend(opts.headers, params.headers);
delete params['headers']
}
if (Utils.isObjEmpty(opts)) opts = undefined;
var body = (params || {})[this.bodyAttr];

@@ -159,3 +162,5 @@

var gateway = new this.Gateway(gatewayOpts);
gateway.setSuccessHandler(this.globalSuccessHandler);
gateway.setErrorHandler(this.globalErrorHandler);
if (Env.USE_PROMISES) return gateway.promisify(callback);

@@ -162,0 +167,0 @@ return gateway.success(callback).call();

@@ -49,34 +49,34 @@ if (typeof window !== 'undefined' && window !== null) {

var options, name, src, copy, clone;
var target = arguments[0] || {};
var length = arguments.length;
var target = arguments[0] || {};
var length = arguments.length;
// Handle case when target is a string or something
if (typeof target !== 'object') target = {};
// Handle case when target is a string or something
if (typeof target !== 'object') target = {};
for (var i = 1; i < length; i++) {
// Only deal with non-null/undefined values
for (var i = 1; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) === null) continue;
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) continue;
// Prevent never-ending loop
if (target === copy) continue;
// Recurse if we're merging plain objects or arrays
if (copy && isObject(copy)) {
clone = src && isObject(src) ? src : {};
// Never move original objects, clone them
target[name] = this.extend(clone, copy);
// Recurse if we're merging plain objects or arrays
if (copy && isObject(copy)) {
clone = src && isObject(src) ? src : {};
// Never move original objects, clone them
target[name] = this.extend(clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
return target;
return target;
},

@@ -83,0 +83,0 @@

@@ -99,2 +99,11 @@ var Mappersmith = require('../index');

describe('#setSuccessHandler', function() {
it('assigns successHandler', function() {
gateway = new Gateway({url: url, method: verb});
expect(gateway.successHandler).to.be.undefined;
gateway.setSuccessHandler(Utils.noop);
expect(gateway.successHandler).to.equal(Utils.noop);
});
});
describe('#call', function() {

@@ -304,2 +313,22 @@ var gateway, performanceNowValue;

});
describe('with a successHandler defined', function() {
it('calls handler with stats object and data', function() {
var data = 'data';
var success = sinon.spy(function() {});
var successHandler = sinon.spy(function() {});
gateway.setSuccessHandler(successHandler);
gateway.success(success);
gateway.successCallback(data);
expect(success).to.have.been.called;
expect(successHandler).to.have.been.deep.calledWith(Utils.extend({}, stats, {
params: params,
headers: {Authorization: 'token'},
timeElapsed: gateway.timeElapsed,
timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed)
}), data);
});
});
});

@@ -306,0 +335,0 @@

@@ -92,2 +92,14 @@ var $ = require('jquery');

describe('extra stats', function() {
it('returns status code', function() {
requestWithGateway(
201,
JSON.stringify(data),
newGateway(Mappersmith.VanillaGateway)
);
var stats = success.args[0][1];
expect(stats).to.not.be.undefined;
expect(stats.status).to.equal(201);
});
it('returns response headers', function() {

@@ -105,20 +117,59 @@ requestWithGateway(

});
describe('when IE returns status 1223 for 204', function() {
it('return status 204', function() {
requestWithGateway(
1223,
JSON.stringify(data),
newGateway(Mappersmith.VanillaGateway)
);
var stats = success.args[0][1];
expect(stats).to.not.be.undefined;
expect(stats.status).to.equal(204);
});
});
});
describe('withCredentials', function() {
it('configures withCredentials in the request', function() {
var xhr;
requestWithGateway(
200,
JSON.stringify(data),
newGateway(Mappersmith.VanillaGateway, {
opts: {
withCredentials: true,
configure: function(request) { xhr = request }
}
})
);
expect(xhr.withCredentials).to.equal(true);
});
});
});
describe('JQueryGateway', function() {
describe('custom opts', function() {
var ajax;
var ajax;
beforeEach(function() {
ajax = {
done: function() {return this},
fail: function() {return this},
always: function() {return this}
};
beforeEach(function() {
ajax = {
done: function() {return this},
fail: function() {return this},
always: function() {return this}
};
sinon.spy(ajax, 'done');
sinon.spy(ajax, 'fail');
sinon.spy(ajax, 'always');
sinon.spy(ajax, 'done');
sinon.spy(ajax, 'fail');
sinon.spy(ajax, 'always');
});
afterEach(function() {
if ($.ajax.restore) $.ajax.restore();
});
describe('custom opts', function() {
beforeEach(function() {
sinon.stub($, 'ajax').returns(ajax);

@@ -128,6 +179,2 @@ method = 'get';

afterEach(function() {
$.ajax.restore();
});
it('merges opts with $.ajax defaults', function() {

@@ -149,2 +196,14 @@ var opts = {jsonp: true};

describe('extra stats', function() {
it('returns status code', function() {
requestWithGateway(
201,
JSON.stringify(data),
newGateway(Mappersmith.JQueryGateway)
);
var stats = success.args[0][1];
expect(stats).to.not.be.undefined;
expect(stats.status).to.equal(201);
});
it('returns response headers', function() {

@@ -162,4 +221,38 @@ requestWithGateway(

});
describe('when IE returns status 1223 for 204', function() {
it('return status 204', function() {
requestWithGateway(
1223,
JSON.stringify(data),
newGateway(Mappersmith.JQueryGateway)
);
var stats = success.args[0][1];
expect(stats).to.not.be.undefined;
expect(stats.status).to.equal(204);
});
});
});
describe('withCredentials', function() {
beforeEach(function() {
sinon.stub($, 'ajax').returns(ajax);
});
it('configures withCredentials in the request', function() {
var opts = {xhrFields: {withCredentials: true}};
var defaults = {url: url};
var config = Utils.extend(defaults, opts);
requestWithGateway(
200,
JSON.stringify(data),
newGateway(Mappersmith.JQueryGateway, {opts: {withCredentials: true}})
);
expect($.ajax).to.have.been.calledWith(config);
});
});
});
});

@@ -51,2 +51,3 @@ var shared = require('shared-examples-for');

test.gateway.prototype.setErrorHandler = function() {};
test.gateway.prototype.setSuccessHandler = function() {};

@@ -59,2 +60,3 @@ sinon.spy(test, 'gateway');

sinon.spy(test.gateway.prototype, 'setErrorHandler');
sinon.spy(test.gateway.prototype, 'setSuccessHandler');

@@ -150,2 +152,10 @@ gateway = test.gateway;

it('calls gateway#setSuccessHandler with globalSuccessHandler', function() {
var successHandler = function() {};
mapper.globalSuccessHandler = successHandler;
var request = mapper.newGatewayRequest({method: method, host: host, path: path});
expect(request(params, callback)).to.be.an.instanceof(gateway);
expect(gateway.prototype.setSuccessHandler).to.have.been.calledWith(successHandler);
});
it('calls gateway#setErrorHandler with globalErrorHandler', function() {

@@ -328,2 +338,51 @@ var errorHandler = function() {};

shared.shouldBehaveLike('merged rules');
describe('matching against dynamic parts of the URL', function() {
beforeEach(function() {
manifest.rules = [{match: /\/v1\/books\/cats\/all\.json/, values: opts}];
mapper = new Mapper(manifest, gateway);
});
it('merge the configured rules', function() {
fullUrl = host + '/v1/books/cats/all.json';
var request = mapper.newGatewayRequest({
method: method,
host: host,
path: '/v1/books/{category}/all.json',
params: {category: 'cats'}
});
expect(request(callback)).to.be.an.instanceof(gateway);
expect(gateway).to.have.been.calledWith({
url: fullUrl,
host: host,
path: '/v1/books/cats/all.json',
params: {category: 'cats'},
method: method,
opts: {matchUrl: true},
processor: opts.processor
});
});
describe('when the dynamic part doesn\'t match', function() {
it('doesn\'t merge the rules', function() {
fullUrl = host + '/v1/books/dogs/all.json';
var request = mapper.newGatewayRequest({
method: method,
host: host,
path: '/v1/books/{category}/all.json',
params: {category: 'dogs'}
});
expect(request(callback)).to.be.an.instanceof(gateway);
expect(gateway).to.have.been.calledWith({
url: fullUrl,
host: host,
path: '/v1/books/dogs/all.json',
params: {category: 'dogs'},
method: method
});
});
});
});
});

@@ -514,2 +573,11 @@

describe('when calling "onSuccess" on the returned object', function() {
it('assigns the global success handler', function() {
var successHandler = function() {};
expect(mapper.globalSuccessHandler).to.equal(Utils.noop);
result.onSuccess(successHandler);
expect(mapper.globalSuccessHandler).to.equal(successHandler);
});
});
describe('when calling "onError" on the returned object', function() {

@@ -516,0 +584,0 @@ it('assigns the global error handler', function() {

@@ -25,3 +25,2 @@ require('./test-helper');

describe('NodeVanillaGateway', function() {

@@ -33,3 +32,3 @@ describe('extra stats', function() {

get(path).
reply(200, JSON.stringify(data));
reply(201, JSON.stringify(data));

@@ -42,2 +41,8 @@ newGateway().

it('returns status code', function() {
var stats = success.args[0][1];
expect(stats).to.not.be.undefined;
expect(stats.status).to.equal(201);
});
it('returns response headers', function() {

@@ -49,5 +54,4 @@ var stats = success.args[0][1];

});
});
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc