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.5.0 to 0.6.0

CHANGELOG.md

99

build/mappersmith.js

@@ -60,2 +60,6 @@ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Mappersmith=e()}}(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){

this.timeStart = null;
this.timeEnd = null;
this.timeElapsed = null;
this.successCallback = Utils.noop;

@@ -69,2 +73,3 @@ this.failCallback = Utils.noop;

call: function() {
this.timeStart = Utils.performanceNow();
this[this.method].apply(this, arguments);

@@ -75,9 +80,17 @@ return this;

success: function(callback) {
if (this.processor !== undefined) {
this.successCallback = function(data) {
callback(this.processor(data));
}
} else {
this.successCallback = callback;
}
this.successCallback = function(data, extraStats) {
this.timeEnd = Utils.performanceNow();
this.timeElapsed = this.timeEnd - this.timeStart;
if (this.processor) data = this.processor(data);
var stats = Utils.extend({
url: this.url,
params: this.params,
timeElapsed: this.timeElapsed,
timeElapsedHumanized: Utils.humanizeTimeElapsed(this.timeElapsed)
}, extraStats);
callback(data, stats);
}.bind(this);
return this;

@@ -177,5 +190,5 @@ },

jQuery.ajax(Utils.extend({url: this.url}, config)).
done(function() { this.successCallback.apply(this, arguments) }.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() { this.failCallback.apply(this, arguments) }.bind(this)).
always(function() { this.completeCallback.apply(this, arguments) }.bind(this));
}

@@ -338,8 +351,15 @@

urlFor: function(path, urlParams) {
urlFor: function(path, urlParams, host) {
// using `Utils.extend` avoids undesired changes to `urlParams`
var params = Utils.extend({}, urlParams);
var normalizedPath = /^\//.test(path) ? path : '/' + path;
var host = this.host.replace(/\/$/, '');
var normalizedPath = path;
if (typeof host === "undefined" || host === null) host = this.host;
if (host === false) host = '';
host = host.replace(/\/$/, '');
if (host !== '') {
normalizedPath = /^\//.test(path) ? path : '/' + path;
}
// does not includes the body param into the URL

@@ -390,7 +410,7 @@ delete params[this.bodyAttr];

opts = Utils.extend({}, opts, rules.gateway);
if(Utils.isObjEmpty(opts)) opts = undefined;
if (Utils.isObjEmpty(opts)) opts = undefined;
var body = (params || {})[this.bodyAttr];
var gatewayOpts = Utils.extend({}, {
url: this.urlFor(descriptor.path, params),
url: this.urlFor(descriptor.path, params, descriptor.host),
method: descriptor.method,

@@ -415,2 +435,28 @@ processor: descriptor.processor || rules.processor,

},{"./utils":8}],8:[function(require,module,exports){
(function (process){
if (typeof window !== 'undefined' && window !== null) {
window.performance = window.performance || {};
performance.now = (function() {
return performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function() { return new Date().getTime(); };
})();
}
var hasProcessHrtime = function() {
return (typeof process !== 'undefined' && process !== null) && process.hrtime;
}
var getNanoSeconds, loadTime;
if (hasProcessHrtime()) {
getNanoSeconds = function() {
var hr = process.hrtime();
return hr[0] * 1e9 + hr[1];
}
loadTime = getNanoSeconds();
}
var Utils = {

@@ -482,2 +528,22 @@ r20: /%20/g,

/*
* Gives time in miliseconds, but with sub-milisecond precision for Browser
* and Nodejs
*/
performanceNow: function() {
if (hasProcessHrtime()) {
return (getNanoSeconds() - loadTime) / 1e6;
}
return performance.now();
},
humanizeTimeElapsed: function(timeElapsed) {
if (timeElapsed >= 1000.0) {
return (timeElapsed / 1000.0).toFixed(2) + ' s';
}
return timeElapsed.toFixed(2) + ' ms';
},
Exception: function(message) {

@@ -491,3 +557,4 @@ this.message = message;

},{}]},{},[1])(1)
}).call(this,require('_process'))
},{"_process":undefined}]},{},[1])(1)
});

2

build/mappersmith.min.js
/*! Mappersmith - https://github.com/tulios/mappersmith - Generated by browserify */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Mappersmith=e()}}(function(){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){module.exports={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/forge":3,"./src/gateway":4,"./src/gateway/jquery-gateway":5,"./src/gateway/vanilla-gateway":6,"./src/mapper":7,"./src/utils":8}],2:[function(require,module){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":4,"./utils":8}],3:[function(require,module){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":6,"./mapper":7}],4:[function(require,module){var Utils=require("./utils"),Gateway=function(args){this.url=args.url,this.method=args.method,this.processor=args.processor,this.params=args.params||{},this.body=args.body,this.opts=args.opts||{},this.successCallback=Utils.noop,this.failCallback=Utils.noop,this.completeCallback=Utils.noop};Gateway.prototype={call:function(){return this[this.method].apply(this,arguments),this},success:function(callback){return this.successCallback=void 0!==this.processor?function(data){callback(this.processor(data))}:callback,this},fail:function(callback){return this.failCallback=callback,this},complete:function(callback){return this.completeCallback=callback,this},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},{"./utils":8}],5:[function(require,module){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(this.opts.header,{"X-HTTP-Method-Override":method}));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.apply(this,arguments)}.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":8}],6:[function(require,module){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),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");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)},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":8}],7:[function(require,module){var Utils=require("./utils"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.host=this.manifest.host,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:{}})},urlFor:function(path,urlParams){var params=Utils.extend({},urlParams),normalizedPath=/^\//.test(path)?path:"/"+path,host=this.host.replace(/\/$/,"");delete params[this.bodyAttr],Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(normalizedPath)&&(normalizedPath=normalizedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),host+normalizedPath+paramsString},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 body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:this.urlFor(descriptor.path,params),method:descriptor.method,processor:descriptor.processor||rules.processor,params:params,body:body,opts:opts});return new this.Gateway(gatewayOpts).success(callback).call()}.bind(this)}},module.exports=Mapper},{"./utils":8}],8:[function(require,module){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,"+")},Exception:function(message){this.message=message,this.toString=function(){return"[Mappersmith] "+this.message}}};module.exports=Utils},{}]},{},[1])(1)});
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Mappersmith=e()}}(function(){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){module.exports={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/forge":3,"./src/gateway":4,"./src/gateway/jquery-gateway":5,"./src/gateway/vanilla-gateway":6,"./src/mapper":7,"./src/utils":8}],2:[function(require,module){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":4,"./utils":8}],3:[function(require,module){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":6,"./mapper":7}],4:[function(require,module){var Utils=require("./utils"),Gateway=function(args){this.url=args.url,this.method=args.method,this.processor=args.processor,this.params=args.params||{},this.body=args.body,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(),this[this.method].apply(this,arguments),this},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 stats=Utils.extend({url:this.url,params:this.params,timeElapsed:this.timeElapsed,timeElapsedHumanized:Utils.humanizeTimeElapsed(this.timeElapsed)},extraStats);callback(data,stats)}.bind(this),this},fail:function(callback){return this.failCallback=callback,this},complete:function(callback){return this.completeCallback=callback,this},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},{"./utils":8}],5:[function(require,module){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(this.opts.header,{"X-HTTP-Method-Override":method}));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":8}],6:[function(require,module){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),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");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)},_isContentTypeJSON:function(request){return/application\/json/.test(request.getResponseHeader("Content-Type"))}});module.exports=VanillaGateway},{"../create-gateway":2,"../utils":8}],7:[function(require,module){var Utils=require("./utils"),Mapper=function(manifest,Gateway,bodyAttr){this.manifest=manifest,this.host=this.manifest.host,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:{}})},urlFor:function(path,urlParams,host){var params=Utils.extend({},urlParams),normalizedPath=path;("undefined"==typeof host||null===host)&&(host=this.host),host===!1&&(host=""),host=host.replace(/\/$/,""),""!==host&&(normalizedPath=/^\//.test(path)?path:"/"+path),delete params[this.bodyAttr],Object.keys(params).forEach(function(key){var value=params[key],pattern="{"+key+"}";new RegExp(pattern).test(normalizedPath)&&(normalizedPath=normalizedPath.replace("{"+key+"}",value),delete params[key])});var paramsString=Utils.params(params);return 0!==paramsString.length&&(paramsString="?"+paramsString),host+normalizedPath+paramsString},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 body=(params||{})[this.bodyAttr],gatewayOpts=Utils.extend({},{url:this.urlFor(descriptor.path,params,descriptor.host),method:descriptor.method,processor:descriptor.processor||rules.processor,params:params,body:body,opts:opts});return new this.Gateway(gatewayOpts).success(callback).call()}.bind(this)}},module.exports=Mapper},{"./utils":8}],8:[function(require,module){(function(process){"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 getNanoSeconds,loadTime,hasProcessHrtime=function(){return"undefined"!=typeof process&&null!==process&&process.hrtime};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){this.message=message,this.toString=function(){return"[Mappersmith] "+this.message}}};module.exports=Utils}).call(this,require("_process"))},{_process:void 0}]},{},[1])(1)});
{
"name": "mappersmith",
"version": "0.5.0",
"version": "0.6.0",
"description": "It is a lightweight rest client mapper for javascript",

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

"scripts": {
"build": "./node_modules/.bin/browserify index.js -s Mappersmith -o build/mappersmith.js",
"build": "./node_modules/.bin/browserify index.js -s Mappersmith --no-builtins -o build/mappersmith.js",
"build-test": "./node_modules/.bin/browserify index.js -t rewireify -s Mappersmith -o build/mappersmith.test.js",

@@ -15,0 +15,0 @@ "release": "npm run build && ./node_modules/.bin/uglifyjs build/mappersmith.js -o build/mappersmith.min.js -c --screw-ie8 --preamble '/*! Mappersmith - https://github.com/tulios/mappersmith - Generated by browserify */'",

[![npm version](https://badge.fury.io/js/mappersmith.svg)](http://badge.fury.io/js/mappersmith)
# Mappersmith
**Mappersmith** is a lightweight, dependency-free, rest client mapper for javascript. It helps you map your API to use at the client and/or server, giving you all the flexibility you want to customize requests or write your own gateways.
**Mappersmith** is a lightweight, isomorphic, dependency-free, rest client mapper for javascript. It helps you map your API to use at the client and/or server, giving you all the flexibility you want to customize requests or write your own gateways.
https://www.npmjs.com/package/mappersmith
## Install

@@ -96,6 +98,8 @@

The __default stats__ in the object are: `timeElapsed` and `timeElapsedHumanized`. Example:
The __default stats__ in the object are: `url`, `params`, `timeElapsed` and `timeElapsedHumanized`. Example:
```javascript
{
url: 'http://my.api.com/v1/books.json?language=en',
params: {language: 'en'},
timeElapsed: 6.745000369846821,

@@ -191,2 +195,29 @@ timeElapsedHumanized: '6.75 ms'

#### Alternative host
There are some cases where a resource method reside in another host, in those cases you can use the `host` key to configure a new host or to disable the resolution.
```javascript
var manifest = {
host: 'http://new-host.com/api/v2',
resources: {
MyResouce: {
all: {path: '/all.json'},
byId: {path: '/{id}.json', host: 'http://old-host.com/api/v1'},
other: {path: '{url}', host: false}
}
}
}
var Client = Mappersmith.forge(manifest);
Client.MyResource.all()
// http://new-host.com/api/v2/all.json
Client.MyResource.byId({id: 1})
// http://old-host.com/api/v1/1.json
Client.MyResource.other({url: 'http://host.com/other/'})
// http://host.com/other/
```
#### Compact Syntax

@@ -389,4 +420,10 @@ If you find tiring having to map your API methods with hashes, you can use our incredible compact syntax:

## Contributors
Check it out!
https://github.com/tulios/mappersmith/graphs/contributors
## Licence
See [LICENCE](https://github.com/tulios/mappersmith/blob/master/LICENSE) for more details.

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

var stats = Utils.extend({
url: this.url,
params: this.params,
timeElapsed: this.timeElapsed,

@@ -47,0 +49,0 @@ timeElapsedHumanized: Utils.humanizeTimeElapsed(this.timeElapsed)

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

urlFor: function(path, urlParams) {
urlFor: function(path, urlParams, host) {
// using `Utils.extend` avoids undesired changes to `urlParams`
var params = Utils.extend({}, urlParams);
var normalizedPath = /^\//.test(path) ? path : '/' + path;
var host = this.host.replace(/\/$/, '');
var normalizedPath = path;
if (typeof host === "undefined" || host === null) host = this.host;
if (host === false) host = '';
host = host.replace(/\/$/, '');
if (host !== '') {
normalizedPath = /^\//.test(path) ? path : '/' + path;
}
// does not includes the body param into the URL

@@ -105,7 +112,7 @@ delete params[this.bodyAttr];

opts = Utils.extend({}, opts, rules.gateway);
if(Utils.isObjEmpty(opts)) opts = undefined;
if (Utils.isObjEmpty(opts)) opts = undefined;
var body = (params || {})[this.bodyAttr];
var gatewayOpts = Utils.extend({}, {
url: this.urlFor(descriptor.path, params),
url: this.urlFor(descriptor.path, params, descriptor.host),
method: descriptor.method,

@@ -112,0 +119,0 @@ processor: descriptor.processor || rules.processor,

@@ -88,6 +88,7 @@ var expect = chai.expect;

describe('#success', function() {
var gateway;
var gateway, params;
beforeEach(function() {
gateway = new Gateway({url: url, method: verb});
params = {a: 1, b: false};
gateway = new Gateway({url: url, params: params, method: verb});
});

@@ -126,5 +127,7 @@

it('calls the callback with data and stats object (with timeElapsed and timeElapsedHumanized keys)', function() {
it('calls the callback with data and stats object', function() {
gateway.successCallback(data);
expect(success).to.have.been.deep.calledWith(data, {
url: url,
params: params,
timeElapsed: gateway.timeElapsed,

@@ -135,3 +138,3 @@ timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed)

it('merges extraStats with default stats (timeElapsed and timeElapsedHumanized)', function() {
it('merges extraStats with default stats', function() {
var extraStats = {

@@ -143,2 +146,4 @@ a: 1,

expect(success).to.have.been.deep.calledWith(data, Utils.extend({
url: url,
params: params,
timeElapsed: gateway.timeElapsed,

@@ -150,3 +155,3 @@ timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed)

describe('with a configured processor', function() {
it('calls the callback with processed data and stats object (with timeElapsed and timeElapsedHumanized keys)', function() {
it('calls the callback with processed data and stats object', function() {
var processedData = 'new';

@@ -156,2 +161,4 @@ gateway.processor = function(data) { return processedData };

expect(success).to.have.been.deep.calledWith(processedData, {
url: url,
params: params,
timeElapsed: gateway.timeElapsed,

@@ -158,0 +165,0 @@ timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed)

@@ -20,2 +20,4 @@ var expect = chai.expect;

byId: {path: '/v1/books/{id}.json'},
byUrl: {path: '{url}', host: ''},
AltById: {path: '/v1/books/{id}.json', host: 'http://alt-url'},
archived: '/v1/books/archived.json',

@@ -324,2 +326,38 @@ byCategory: 'get:/v1/books/{category}/all.json'

});
describe('explicit empty host with "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('/path', null, '')).to.equals('/path');
});
});
describe('explicit empty host without "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('path', null, '')).to.equals('path');
});
});
describe('explicit empty host, specified by false, with "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('/path', null, false)).to.equals('/path');
});
});
describe('explicit empty host, specified by false, without "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('path', null, false)).to.equals('path');
});
});
describe('explicit host with "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('/path', null, 'http://alt-url')).to.equals('http://alt-url/path');
});
});
describe('explicit host without "/"', function() {
it('returns host and path', function() {
expect(mapper.urlFor('path', null, 'http://alt-url')).to.equals('http://alt-url/path');
});
});
});

@@ -373,2 +411,4 @@

expect(result.Book.byId).to.be.a('function');
expect(result.Book.byUrl).to.be.a('function');
expect(result.Book.AltById).to.be.a('function');
expect(result.Book.archived).to.be.a('function');

@@ -448,2 +488,38 @@ expect(result.Photo.byCategory).to.be.a('function');

describe('with params in the path and query string and alternate empty host', function() {
it('calls the gateway with the configured values', function() {
var path = manifest.resources.Book.byUrl.path;
var host = manifest.resources.Book.byUrl.host;
var paramUrl = 'http://alt-full-url/v1/books/1.json';
var params = {url: paramUrl};
var url = mapper.urlFor(path, params, host);
result.Book.byUrl(params, callback);
expect(gateway).to.have.been.calledWith({
url: url,
method: method,
params: params
});
expect(gateway.prototype.success).to.have.been.calledWith(callback);
});
});
describe('with params in the path and query string and alternate host', function() {
it('calls the gateway with the configured values', function() {
var path = manifest.resources.Book.AltById.path;
var host = manifest.resources.Book.AltById.host;
var params = {id: 3, d: 4};
var url = mapper.urlFor(path, params, host);
result.Book.AltById(params, callback);
expect(gateway).to.have.been.calledWith({
url: url,
method: method,
params: params
});
expect(gateway.prototype.success).to.have.been.calledWith(callback);
});
});
describe('with non-default method', function() {

@@ -450,0 +526,0 @@ it('calls the gateway with the configured values', function() {

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