Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

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.10.0 to 0.11.0

10

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.10.0, Fixture support
* Mappersmith 0.11.0, Fixture support
* https://github.com/tulios/mappersmith

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

this.opts.success = false;
this.opts.errorParams = Utils.extend({status: 400}, params || {});
return this;

@@ -78,3 +79,8 @@ },

this.opts.calls.push(requestedResource);
return this.data();
var data = this.data();
var errorParams = this.opts.errorParams || {};
var errorObj = {status: errorParams.status, args: [data]};
return this.isSuccess() ? data : errorObj;
},

@@ -81,0 +87,0 @@

66

build/mappersmith.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.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.10.0
* Mappersmith 0.11.0
* https://github.com/tulios/mappersmith

@@ -84,5 +84,5 @@ */

this.successCallback = Utils.noop;
this.failCallback = Utils.noop;
this.completeCallback = Utils.noop;
this.success(Utils.noop);
this.fail(Utils.noop);
this.complete(Utils.noop);
}

@@ -166,11 +166,13 @@

fail: function(callback) {
this.failCallback = function() {
var args = [this.getRequestedResource()];
this.failCallback = function(errorObj) {
errorObj = errorObj || {status: 400, args: []};
var gatewayArgs = Array.prototype.slice.call(errorObj.args);
var status = errorObj.status;
var resource = this.getRequestedResource();
var errorResource = Utils.extend({status: status}, resource);
var args = [errorResource].concat(gatewayArgs);
var proceed = true;
// remember, `arguments` isn't an array
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
callback.apply(this, args);
if (this.errorHandler) proceed = !(this.errorHandler.apply(this, args) === true);
if (proceed) callback.apply(this, args);
}.bind(this);

@@ -195,2 +197,6 @@

setErrorHandler: function(errorHandler) {
this.errorHandler = errorHandler;
},
shouldEmulateHTTP: function(method) {

@@ -277,5 +283,14 @@ return !!(this.opts.emulateHTTP && /^(delete|put|patch)/i.test(method));

jQuery.ajax(Utils.extend({url: this.url}, config)).
done(function() { this.successCallback(arguments[0]) }.bind(this)).
fail(function() { this.failCallback.apply(this, arguments) }.bind(this)).
always(function() { this.completeCallback.apply(this, arguments) }.bind(this));
done(function() {
this.successCallback(arguments[0]);
}.bind(this)).
fail(function(jqXHR) {
this.failCallback({status: jqXHR.status, args: arguments});
}.bind(this)).
always(function() {
this.completeCallback.apply(this, arguments);
}.bind(this));
}

@@ -345,5 +360,6 @@

var data = null;
var status = request.status;
try {
if (request.status >= 200 && request.status < 400) {
if (status >= 200 && status < 400) {
if (this._isContentTypeJSON(request)) {

@@ -359,6 +375,6 @@ data = JSON.parse(request.responseText);

} else {
this.failCallback(request);
this.failCallback({status: status, args: [request]});
}
} catch(e) {
this.failCallback(request);
this.failCallback({status: status, args: [request]});

@@ -372,3 +388,3 @@ } finally {

request.onerror = function() {
this.failCallback.apply(this, arguments);
this.failCallback({status: 400, args: [arguments]});
this.completeCallback.apply(this, arguments);

@@ -413,2 +429,3 @@ }.bind(this);

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

@@ -424,5 +441,13 @@

return context;
}, {});
}, this.createContext());
},
createContext: function() {
var errorAssigner = function(handler) {
this.globalErrorHandler = handler;
}.bind(this);
return {onError: errorAssigner};
},
buildResource: function(resourceName) {

@@ -534,2 +559,3 @@ var methods = this.manifest.resources[resourceName];

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

@@ -536,0 +562,0 @@ return gateway.success(callback).call();

!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.10.0
* Mappersmith 0.11.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.successCallback=Utils.noop,this.failCallback=Utils.noop,this.completeCallback=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(){for(var args=[this.getRequestedResource()],i=0;i<arguments.length;i++)args.push(arguments[i]);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}},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(){this.successCallback(arguments[0])}.bind(this)).fail(function(){this.failCallback.apply(this,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;try{request.status>=200&&request.status<400?(data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText,this.successCallback(data)):this.failCallback(request)}catch(e){this.failCallback(request)}finally{this.completeCallback(data,request)}}.bind(this),request.onerror=function(){this.failCallback.apply(this,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};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},{})},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],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),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 Env.USE_PROMISES?gateway.promisify(callback):gateway.success(callback).call()}.bind(this)}},module.exports=Mapper},{"./env":3,"./utils":9}],9:[function(require,module,exports){"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 hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime},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){out=out||{};for(var i=1;i<arguments.length;i++)if(arguments[i])for(var key in arguments[i])arguments[i].hasOwnProperty(key)&&void 0!==arguments[i][key]&&(out[key]=arguments[i][key]);return out},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,"+")},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);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}},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(){this.successCallback(arguments[0])}.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{status>=200&&400>status?(data=this._isContentTypeJSON(request)?JSON.parse(request.responseText):request.responseText,this.successCallback(data)):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],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),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){"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 hasProcessHrtime=function(){return"undefined"!=typeof _process&&null!==_process&&_process.hrtime},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){out=out||{};for(var i=1;i<arguments.length;i++)if(arguments[i])for(var key in arguments[i])arguments[i].hasOwnProperty(key)&&void 0!==arguments[i][key]&&(out[key]=arguments[i][key]);return out},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,"+")},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.11.0
- Method to configure a global error handler per client
- Included status code in the error request object
## 0.10.0

@@ -4,0 +9,0 @@

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

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

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

__Mappersmith supports Promises, check [how to enable](#using-with-promises) in a section bellow__
__Mappersmith supports Promises, check [how to enable](#using-with-promises) in a section below__

@@ -123,3 +123,3 @@ ### Success callback arguments

The fail callback will receive in the first argument the requested resource, which is an object that contains the requested URL, host, path and params. From the second argument and beyond it will receive the error objects from the specific gateway implementations.
The fail callback will receive in the first argument the requested resource, which is an object that contains the requested URL, host, path, status and params. From the second argument and beyond it will receive the error objects from the specific gateway implementations.

@@ -131,5 +131,8 @@ ```javascript

console.log(request.params) // {id: 3}
console.log(request.status) // 503
});
```
It's possible to assign a global error handler, take a look in a [section below](#global-error-handling)
### Parameters

@@ -283,2 +286,3 @@

console.log(err.response); // requested resource, same as stats
console.log(err.response.status); // status code from the request (e.g: 503, 404, etc)
console.log(err.err); // array of errors given by gateway

@@ -325,2 +329,16 @@ });

### <a name="global-error-handling"></a> Global error handling
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.
```javascript
Client.onError(function(request, err) {
console.log(request.url) // 'http://my.api.com/v1/books/3.json'
console.log(request.params) // {id: 3}
console.log(request.status) // 503
});
```
The global handler runs before the local callback, to skip the local handler return `true`.
### Compact Syntax

@@ -573,6 +591,16 @@ If you find tiring having to map your API methods with hashes, you can use our incredible compact syntax:

matching({url: 'http://full-url/v1/books.json'}).
failure().
failure(). // status 400 by default
response(data);
```
It's possible to define the status code of the failed request:
```javascript
var fixture = Mappersmith.Env.Fixture.
define('get').
matching({url: 'http://full-url/v1/books.json'}).
failure({status: 503}).
response(data);
```
The fixture object contains some methods to help you with your tests. Using the variable `fixture` from the last example, you can call:

@@ -579,0 +607,0 @@

@@ -20,2 +20,3 @@ var Utils = require('mappersmith').Utils;

this.opts.success = false;
this.opts.errorParams = Utils.extend({status: 400}, params || {});
return this;

@@ -59,3 +60,8 @@ },

this.opts.calls.push(requestedResource);
return this.data();
var data = this.data();
var errorParams = this.opts.errorParams || {};
var errorObj = {status: errorParams.status, args: [data]};
return this.isSuccess() ? data : errorObj;
},

@@ -62,0 +68,0 @@

@@ -32,5 +32,5 @@ var Env = require('./env');

this.successCallback = Utils.noop;
this.failCallback = Utils.noop;
this.completeCallback = Utils.noop;
this.success(Utils.noop);
this.fail(Utils.noop);
this.complete(Utils.noop);
}

@@ -114,11 +114,13 @@

fail: function(callback) {
this.failCallback = function() {
var args = [this.getRequestedResource()];
this.failCallback = function(errorObj) {
errorObj = errorObj || {status: 400, args: []};
var gatewayArgs = Array.prototype.slice.call(errorObj.args);
var status = errorObj.status;
var resource = this.getRequestedResource();
var errorResource = Utils.extend({status: status}, resource);
var args = [errorResource].concat(gatewayArgs);
var proceed = true;
// remember, `arguments` isn't an array
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
callback.apply(this, args);
if (this.errorHandler) proceed = !(this.errorHandler.apply(this, args) === true);
if (proceed) callback.apply(this, args);
}.bind(this);

@@ -143,2 +145,6 @@

setErrorHandler: function(errorHandler) {
this.errorHandler = errorHandler;
},
shouldEmulateHTTP: function(method) {

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

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

jQuery.ajax(Utils.extend({url: this.url}, config)).
done(function() { this.successCallback(arguments[0]) }.bind(this)).
fail(function() { this.failCallback.apply(this, arguments) }.bind(this)).
always(function() { this.completeCallback.apply(this, arguments) }.bind(this));
done(function() {
this.successCallback(arguments[0]);
}.bind(this)).
fail(function(jqXHR) {
this.failCallback({status: jqXHR.status, args: arguments});
}.bind(this)).
always(function() {
this.completeCallback.apply(this, arguments);
}.bind(this));
}

@@ -58,0 +67,0 @@

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

response.on('end', function() {
var status = response.statusCode;
try {
if (response.statusCode >= 200 && response.statusCode < 400) {
if (status >= 200 && status < 400) {
if (this.isContentTypeJSON(response)) data = JSON.parse(data);

@@ -58,7 +58,7 @@ this.successCallback(data);

} else {
this.failCallback(response);
this.failCallback({status: status, args: [response]});
}
} catch(e) {
this.failCallback(response, e);
this.failCallback({status: status, args: [response, e]});

@@ -73,3 +73,3 @@ } finally {

onError: function() {
this.failCallback.apply(this, arguments);
this.failCallback({status: 400, args: arguments});
this.completeCallback.apply(this, arguments);

@@ -76,0 +76,0 @@ },

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

var data = null;
var status = request.status;
try {
if (request.status >= 200 && request.status < 400) {
if (status >= 200 && status < 400) {
if (this._isContentTypeJSON(request)) {

@@ -72,6 +73,6 @@ data = JSON.parse(request.responseText);

} else {
this.failCallback(request);
this.failCallback({status: status, args: [request]});
}
} catch(e) {
this.failCallback(request);
this.failCallback({status: status, args: [request]});

@@ -85,3 +86,3 @@ } finally {

request.onerror = function() {
this.failCallback.apply(this, arguments);
this.failCallback({status: 400, args: [arguments]});
this.completeCallback.apply(this, arguments);

@@ -88,0 +89,0 @@ }.bind(this);

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

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

@@ -27,5 +28,13 @@

return context;
}, {});
}, this.createContext());
},
createContext: function() {
var errorAssigner = function(handler) {
this.globalErrorHandler = handler;
}.bind(this);
return {onError: errorAssigner};
},
buildResource: function(resourceName) {

@@ -137,2 +146,3 @@ var methods = this.manifest.resources[resourceName];

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

@@ -139,0 +149,0 @@ return gateway.success(callback).call();

@@ -107,3 +107,3 @@ var Mappersmith = require('../index');

it('allows fixtures for failed requests', function(done) {
it('allows fixtures for failed requests, default status error 400', function(done) {
Mappersmith.Env.Fixture.

@@ -121,2 +121,3 @@ define('get').

expect(err.err).to.eql(['error']);
expect(err.request.status).to.eql(400);
done();

@@ -130,2 +131,24 @@

it('allows fixtures for failed requests with custom status', function(done) {
Mappersmith.Env.Fixture.
define('get').
matching({path: '/v1/books.json'}).
failure({status: 503}).
response('error');
client.Book.all().then(function(result) {
done(new Error('should have called "catch"'));
}).catch(function(err) {
try {
expect(err.err).to.eql(['error']);
expect(err.request.status).to.eql(503);
done();
} catch(e) {
done(e);
}
});
});
['post', 'put', 'delete', 'patch'].forEach(function(method) {

@@ -336,3 +359,3 @@

it('allows fixtures for failed requests', function(done) {
it('allows fixtures for failed requests, default status error 400', function(done) {
Mappersmith.Env.Fixture.

@@ -350,2 +373,3 @@ define('get').

expect(err).to.eql('error');
expect(request.status).to.eql(400);
done();

@@ -358,2 +382,24 @@

});
it('allows fixtures for failed requests with custom status', function(done) {
Mappersmith.Env.Fixture.
define('get').
matching({path: '/v1/books.json'}).
failure({status: 503}).
response('error');
client.Book.all(function() {
done(new Error('should have called "fail"'));
}).fail(function(request, err) {
try {
expect(err).to.eql('error');
expect(request.status).to.eql(503);
done();
} catch(e) {
done(e);
}
});
});
});

@@ -360,0 +406,0 @@

@@ -36,14 +36,23 @@ var Mappersmith = require('../index');

it('configures successCallback with noop', function() {
sinon.spy(Utils, 'noop');
gateway = new Gateway({url: url, method: verb});
expect(gateway.successCallback).to.equals(noop);
gateway.successCallback();
expect(Utils.noop).to.have.been.called;
Utils.noop.restore();
});
it('configures failCallback with noop', function() {
sinon.spy(Utils, 'noop');
gateway = new Gateway({url: url, method: verb});
expect(gateway.failCallback).to.equals(noop);
gateway.failCallback();
expect(Utils.noop).to.have.been.called;
Utils.noop.restore();
});
it('configures completeCallback with noop', function() {
sinon.spy(Utils, 'noop');
gateway = new Gateway({url: url, method: verb});
expect(gateway.completeCallback).to.equals(noop);
gateway.completeCallback();
expect(Utils.noop).to.have.been.called;
Utils.noop.restore();
});

@@ -76,2 +85,11 @@

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

@@ -183,2 +201,3 @@ var gateway, performanceNowValue;

params: params,
status: 400
});

@@ -193,3 +212,3 @@

gateway.failCallback(error1, error2);
gateway.failCallback({status: 400, args: [error1, error2]});
});

@@ -311,3 +330,3 @@ });

gateway.fail(fail);
gateway.failCallback(error1, error2);
gateway.failCallback({status: 400, args: [error1, error2]});
expect(fail).to.have.been.deep.calledWith({

@@ -318,2 +337,3 @@ url: url,

params: params,
status: 400
}, error1, error2);

@@ -325,2 +345,44 @@ });

});
describe('with a errorHandler defined', function() {
it('calls handler with the requested object and the errors list', function() {
var error1 = 'error1';
var error2 = 'error2';
var fail = sinon.spy(function() {});
var errorHandler = sinon.spy(function() {});
gateway.setErrorHandler(errorHandler);
gateway.fail(fail);
gateway.failCallback({status: 400, args: [error1, error2]});
expect(fail).to.have.been.called;
expect(errorHandler).to.have.been.deep.calledWith({
url: url,
host: host,
path: path,
params: params,
status: 400
}, error1, error2);
});
it('returning true, skips the local error callback', function() {
var error1 = 'error1';
var error2 = 'error2';
var fail = sinon.spy(function() {});
var errorHandler = sinon.spy(function() { return true });
gateway.setErrorHandler(errorHandler);
gateway.fail(fail);
gateway.failCallback({status: 400, args: [error1, error2]});
expect(fail).to.not.have.been.called;
expect(errorHandler).to.have.been.deep.calledWith({
url: url,
host: host,
path: path,
params: params,
status: 400
}, error1, error2);
});
});
});

@@ -327,0 +389,0 @@

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

test.gateway.prototype.promisify = function() {return Promise.resolve(true)};
test.gateway.prototype.setErrorHandler = function() {};

@@ -57,2 +58,3 @@ sinon.spy(test, 'gateway');

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

@@ -128,3 +130,3 @@ gateway = test.gateway;

it('returns a function', function() {
var output = typeof mapper.newGatewayRequest(method, path);
var output = typeof mapper.newGatewayRequest({method: method, path: path});
expect(output).to.equals('function');

@@ -149,2 +151,10 @@ });

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

@@ -446,6 +456,16 @@ shared.examplesFor('path with host "false"', function() {

it('returns an object', function() {
it('returns an object with a method "onError"', function() {
expect(result).to.be.a('object');
expect(result.onError).to.be.a('function');
});
describe('when calling "onError" on the returned object', function() {
it('assigns the global error handler', function() {
var errorHandler = function() {};
expect(mapper.globalErrorHandler).to.equal(Utils.noop);
result.onError(errorHandler);
expect(mapper.globalErrorHandler).to.equal(errorHandler);
});
});
it('creates the namespaces', function() {

@@ -741,3 +761,3 @@ expect(result.Book).to.be.a('object');

it('calls promisify with callback to generate a promise', function() {
var request = mapper.newGatewayRequest(method, path);
var request = mapper.newGatewayRequest({method: method, path: path});
request(params, callback);

@@ -744,0 +764,0 @@ expect(gateway.prototype.promisify).to.have.been.calledWith(callback);

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