mappersmith
Advanced tools
Comparing version 0.7.0 to 0.8.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.8.0 | ||
* https://github.com/tulios/mappersmith | ||
*/ | ||
module.exports = { | ||
Env: require('./src/env'), | ||
Utils: require('./src/utils'), | ||
@@ -13,3 +18,3 @@ Gateway: require('./src/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,exports){ | ||
},{"./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'); | ||
@@ -28,3 +33,8 @@ var Gateway = require('./gateway'); | ||
},{"./gateway":4,"./utils":8}],3:[function(require,module,exports){ | ||
},{"./gateway":5,"./utils":9}],3:[function(require,module,exports){ | ||
module.exports = { | ||
USE_PROMISES: false | ||
} | ||
},{}],4:[function(require,module,exports){ | ||
var Mapper = require('./mapper'); | ||
@@ -41,3 +51,3 @@ var VanillaGateway = require('./gateway/vanilla-gateway'); | ||
},{"./gateway/vanilla-gateway":6,"./mapper":7}],4:[function(require,module,exports){ | ||
},{"./gateway/vanilla-gateway":7,"./mapper":8}],5:[function(require,module,exports){ | ||
var Utils = require('./utils'); | ||
@@ -85,2 +95,24 @@ | ||
promisify: function(thenCallback) { | ||
var promise = new Promise(function(resolve, reject) { | ||
this.success(function(data, stats) { | ||
resolve({data: data, stats: stats}); | ||
}); | ||
this.fail(function() { | ||
var args = []; | ||
for (var i = 0; i < arguments.length; i++) { | ||
args.push(arguments[i]); | ||
} | ||
var request = args.shift(); | ||
reject({request: request, err: args}); | ||
}); | ||
this.call(); | ||
}.bind(this)); | ||
if (thenCallback !== undefined) return promise.then(thenCallback); | ||
return promise; | ||
}, | ||
success: function(callback) { | ||
@@ -91,11 +123,8 @@ this.successCallback = function(data, extraStats) { | ||
if (this.processor) data = this.processor(data); | ||
var requestedResource = this.getRequestedResource(); | ||
var stats = Utils.extend({ | ||
url: this.url, | ||
host: this.host, | ||
path: this.path, | ||
params: this.params, | ||
timeElapsed: this.timeElapsed, | ||
timeElapsedHumanized: Utils.humanizeTimeElapsed(this.timeElapsed) | ||
}, extraStats); | ||
}, requestedResource, extraStats); | ||
@@ -109,3 +138,13 @@ callback(data, stats); | ||
fail: function(callback) { | ||
this.failCallback = callback; | ||
this.failCallback = function() { | ||
var args = [this.getRequestedResource()]; | ||
// remember, `arguments` isn't an array | ||
for (var i = 0; i < arguments.length; i++) { | ||
args.push(arguments[i]); | ||
} | ||
callback.apply(this, args); | ||
}.bind(this); | ||
return this; | ||
@@ -119,2 +158,11 @@ }, | ||
getRequestedResource: function() { | ||
return { | ||
url: this.url, | ||
host: this.host, | ||
path: this.path, | ||
params: this.params | ||
} | ||
}, | ||
shouldEmulateHTTP: function(method) { | ||
@@ -148,3 +196,3 @@ return !!(this.opts.emulateHTTP && /^(delete|put|patch)/i.test(method)); | ||
},{"./utils":8}],5:[function(require,module,exports){ | ||
},{"./utils":9}],6:[function(require,module,exports){ | ||
var Utils = require('../utils'); | ||
@@ -192,3 +240,3 @@ var CreateGateway = require('../create-gateway'); | ||
if (typeof this.body === 'object') this.body._method = method; | ||
this.opts.headers = Utils.extend(this.opts.header, {'X-HTTP-Method-Override': method}); | ||
this.opts.headers = Utils.extend({'X-HTTP-Method-Override': method}, this.opts.headers); | ||
} | ||
@@ -212,3 +260,3 @@ | ||
},{"../create-gateway":2,"../utils":8}],6:[function(require,module,exports){ | ||
},{"../create-gateway":2,"../utils":9}],7:[function(require,module,exports){ | ||
var Utils = require('../utils'); | ||
@@ -311,4 +359,5 @@ var CreateGateway = require('../create-gateway'); | ||
},{"../create-gateway":2,"../utils":8}],7:[function(require,module,exports){ | ||
},{"../create-gateway":2,"../utils":9}],8:[function(require,module,exports){ | ||
var Utils = require('./utils'); | ||
var Env = require('./env'); | ||
@@ -445,5 +494,5 @@ /** | ||
return new this.Gateway(gatewayOpts). | ||
success(callback). | ||
call(); | ||
var gateway = new this.Gateway(gatewayOpts); | ||
if (Env.USE_PROMISES) return gateway.promisify(callback); | ||
return gateway.success(callback).call(); | ||
@@ -457,4 +506,3 @@ }.bind(this); | ||
},{"./utils":8}],8:[function(require,module,exports){ | ||
(function (process){ | ||
},{"./env":3,"./utils":9}],9:[function(require,module,exports){ | ||
if (typeof window !== 'undefined' && window !== null) { | ||
@@ -472,4 +520,8 @@ window.performance = window.performance || {}; | ||
// avoid browserify shim | ||
var _process; | ||
try {_process = eval("process")} catch (e) {} | ||
var hasProcessHrtime = function() { | ||
return (typeof process !== 'undefined' && process !== null) && process.hrtime; | ||
return (typeof _process !== 'undefined' && _process !== null) && _process.hrtime; | ||
} | ||
@@ -480,3 +532,3 @@ | ||
getNanoSeconds = function() { | ||
var hr = process.hrtime(); | ||
var hr = _process.hrtime(); | ||
return hr[0] * 1e9 + hr[1]; | ||
@@ -581,4 +633,3 @@ } | ||
}).call(this,require('_process')) | ||
},{"_process":undefined}]},{},[1])(1) | ||
},{}]},{},[1])(1) | ||
}); |
@@ -1,2 +0,5 @@ | ||
/*! Mappersmith - https://github.com/tulios/mappersmith - Generated by browserify */ | ||
!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(){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){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,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":4,"./utils":8}],3:[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":6,"./mapper":7}],4:[function(require,module,exports){var Utils=require("./utils"),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(),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,host:this.host,path:this.path,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,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(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,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),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,exports){var Utils=require("./utils"),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});return new this.Gateway(gatewayOpts).success(callback).call()}.bind(this)}},module.exports=Mapper},{"./utils":8}],8:[function(require,module,exports){(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)}); | ||
!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.8.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_PROMISES:!1}},{}],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 Utils=require("./utils"),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(),this[this.method].apply(this,arguments),this},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},{"./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),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":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){this.message=message,this.toString=function(){return"[Mappersmith] "+this.message}}};module.exports=Utils},{}]},{},[1])(1)}); |
# Changelog | ||
## 0.8.0 | ||
- Support for Promises | ||
- bugfix: made headers from options higher priority than built-in headers | ||
- Fail callback now receives the requested resource (url, host, path and params). This change breaks the API for fail callback, the original error objects will be available from the second argument and beyond | ||
## 0.7.0 | ||
@@ -4,0 +10,0 @@ |
@@ -0,2 +1,7 @@ | ||
/*! | ||
* Mappersmith __VERSION__ | ||
* https://github.com/tulios/mappersmith | ||
*/ | ||
module.exports = { | ||
Env: require('./src/env'), | ||
Utils: require('./src/utils'), | ||
@@ -3,0 +8,0 @@ Gateway: require('./src/gateway'), |
{ | ||
"name": "mappersmith", | ||
"version": "0.7.0", | ||
"version": "0.8.0", | ||
"description": "It is a lightweight, isomorphic, dependency-free, rest client mapper for javascript", | ||
@@ -12,5 +12,5 @@ "author": "Tulio Ornelas <ornelas.tulio@gmail.com>", | ||
"scripts": { | ||
"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", | ||
"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 */'", | ||
"build": "./node_modules/.bin/browserify index.js -s Mappersmith -t browserify-versionify --no-builtins -o build/mappersmith.js", | ||
"build-test": "./node_modules/.bin/browserify index.js -t browserify-versionify -t rewireify -s Mappersmith -o build/mappersmith.test.js", | ||
"release": "npm run build && ./node_modules/.bin/uglifyjs build/mappersmith.js -o build/mappersmith.min.js -c --screw-ie8 --comments /^\\s*\/*!/", | ||
"test": "./node_modules/.bin/mocha test/node/*-test.js", | ||
@@ -17,0 +17,0 @@ "debug-test": "./node_modules/.bin/mocha --debug-brk test/node/*-test.js", |
@@ -85,3 +85,3 @@ [![npm version](https://badge.fury.io/js/mappersmith.svg)](http://badge.fury.io/js/mappersmith) | ||
// success callback | ||
}).fail(function() { | ||
}).fail(function(request, err) { | ||
// fail callback | ||
@@ -93,2 +93,4 @@ }).complete(function() { | ||
__Mappersmith supports Promises, check how to enable in a section bellow__ | ||
#### Success callback arguments | ||
@@ -113,2 +115,14 @@ | ||
#### Fail 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. | ||
```javascript | ||
... | ||
fail(function(request, err) { | ||
console.log(request.url) // 'http://my.api.com/v1/books/3.json' | ||
console.log(request.params) // {id: 3} | ||
}); | ||
``` | ||
#### Parameters | ||
@@ -244,2 +258,51 @@ | ||
#### Using with Promises | ||
To disable the callback API and enable Promises you must turn on the flag `USE_PROMISES`. | ||
```javascript | ||
Mappersmith.Env.USE_PROMISES = true; | ||
``` | ||
After that, you can forge your client and assume that every method will return a promise. | ||
```javascript | ||
var Client = Mappersmith.forge(manifest); | ||
Client.Book.byId({id: 3}).then(function(response) { | ||
console.log(response.data); | ||
console.log(response.stats); | ||
}).catch(function(err) { | ||
console.log(err.response); | ||
console.log(err.err); | ||
}); | ||
// other example | ||
Client.Book.all().then(function(response) { | ||
return response.data; | ||
}).then(function(data) { | ||
console.log(data); | ||
}) | ||
``` | ||
The first callback, if provided, will be used as a "then" statement, example: | ||
```javascript | ||
Client.Book.all(function() { | ||
console.log(1); | ||
}).then(function() { | ||
console.log(2); | ||
}); | ||
// output: | ||
// 1 | ||
// 2 | ||
``` | ||
It is important to note that Mappersmith __does not apply__ any polyfills. If you are using this with a browser that doesn't support Promises, please apply the polyfill first. One option can be [then/promises](https://github.com/then/promise) | ||
## Gateways | ||
@@ -246,0 +309,0 @@ |
@@ -43,2 +43,24 @@ var Utils = require('./utils'); | ||
promisify: function(thenCallback) { | ||
var promise = new Promise(function(resolve, reject) { | ||
this.success(function(data, stats) { | ||
resolve({data: data, stats: stats}); | ||
}); | ||
this.fail(function() { | ||
var args = []; | ||
for (var i = 0; i < arguments.length; i++) { | ||
args.push(arguments[i]); | ||
} | ||
var request = args.shift(); | ||
reject({request: request, err: args}); | ||
}); | ||
this.call(); | ||
}.bind(this)); | ||
if (thenCallback !== undefined) return promise.then(thenCallback); | ||
return promise; | ||
}, | ||
success: function(callback) { | ||
@@ -49,11 +71,8 @@ this.successCallback = function(data, extraStats) { | ||
if (this.processor) data = this.processor(data); | ||
var requestedResource = this.getRequestedResource(); | ||
var stats = Utils.extend({ | ||
url: this.url, | ||
host: this.host, | ||
path: this.path, | ||
params: this.params, | ||
timeElapsed: this.timeElapsed, | ||
timeElapsedHumanized: Utils.humanizeTimeElapsed(this.timeElapsed) | ||
}, extraStats); | ||
}, requestedResource, extraStats); | ||
@@ -67,3 +86,13 @@ callback(data, stats); | ||
fail: function(callback) { | ||
this.failCallback = callback; | ||
this.failCallback = function() { | ||
var args = [this.getRequestedResource()]; | ||
// remember, `arguments` isn't an array | ||
for (var i = 0; i < arguments.length; i++) { | ||
args.push(arguments[i]); | ||
} | ||
callback.apply(this, args); | ||
}.bind(this); | ||
return this; | ||
@@ -77,2 +106,11 @@ }, | ||
getRequestedResource: function() { | ||
return { | ||
url: this.url, | ||
host: this.host, | ||
path: this.path, | ||
params: this.params | ||
} | ||
}, | ||
shouldEmulateHTTP: function(method) { | ||
@@ -79,0 +117,0 @@ return !!(this.opts.emulateHTTP && /^(delete|put|patch)/i.test(method)); |
@@ -43,3 +43,3 @@ var Utils = require('../utils'); | ||
if (typeof this.body === 'object') this.body._method = method; | ||
this.opts.headers = Utils.extend(this.opts.header, {'X-HTTP-Method-Override': method}); | ||
this.opts.headers = Utils.extend({'X-HTTP-Method-Override': method}, this.opts.headers); | ||
} | ||
@@ -46,0 +46,0 @@ |
@@ -20,5 +20,5 @@ var Utils = require('../utils'); | ||
if (typeof this.body === 'object') this.body._method = method; | ||
opts.headers = Utils.extend({}, opts.headers, { | ||
opts.headers = Utils.extend({}, { | ||
'X-HTTP-Method-Override': method | ||
}); | ||
}, opts.headers); | ||
} | ||
@@ -29,6 +29,6 @@ | ||
if (canIncludeBody) { | ||
opts.headers = Utils.extend({}, opts.headers, { | ||
opts.headers = Utils.extend({}, { | ||
'Content-Type': 'application/x-www-form-urlencoded', | ||
'Content-Length': body.length | ||
}); | ||
}, opts.headers); | ||
} | ||
@@ -35,0 +35,0 @@ |
var Utils = require('./utils'); | ||
var Env = require('./env'); | ||
@@ -133,5 +134,5 @@ /** | ||
return new this.Gateway(gatewayOpts). | ||
success(callback). | ||
call(); | ||
var gateway = new this.Gateway(gatewayOpts); | ||
if (Env.USE_PROMISES) return gateway.promisify(callback); | ||
return gateway.success(callback).call(); | ||
@@ -138,0 +139,0 @@ }.bind(this); |
@@ -13,4 +13,8 @@ if (typeof window !== 'undefined' && window !== null) { | ||
// avoid browserify shim | ||
var _process; | ||
try {_process = eval("process")} catch (e) {} | ||
var hasProcessHrtime = function() { | ||
return (typeof process !== 'undefined' && process !== null) && process.hrtime; | ||
return (typeof _process !== 'undefined' && _process !== null) && _process.hrtime; | ||
} | ||
@@ -21,3 +25,3 @@ | ||
getNanoSeconds = function() { | ||
var hr = process.hrtime(); | ||
var hr = _process.hrtime(); | ||
return hr[0] * 1e9 + hr[1]; | ||
@@ -24,0 +28,0 @@ } |
@@ -93,2 +93,100 @@ var expect = chai.expect; | ||
describe('#promisify', function() { | ||
var gateway, data, params; | ||
beforeEach(function() { | ||
data = 'data'; | ||
params = {a: 1, b: false}; | ||
gateway = new Gateway({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
params: params, | ||
method: verb | ||
}); | ||
}); | ||
it('returns a Promise', function() { | ||
expect(gateway.promisify()).to.be.an.instanceof(Promise); | ||
}); | ||
describe('when a callback is provided', function() { | ||
it('configures the first "then"', function(done) { | ||
var callback = sinon.spy(function() {}); | ||
gateway.promisify(callback).then(function() { | ||
expect(callback).to.have.been.calledWith({ | ||
data: data, | ||
stats: { | ||
url: url, | ||
host: host, | ||
path: path, | ||
params: params, | ||
timeElapsed: gateway.timeElapsed, | ||
timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed) | ||
} | ||
}); | ||
done(); | ||
}).catch(function(err) { | ||
done(err); | ||
}); | ||
gateway.successCallback(data); | ||
}); | ||
}); | ||
describe('when success is called', function() { | ||
it('resolves with {data, stats}', function(done) { | ||
gateway.promisify().then(function(result) { | ||
expect(result.data).to.eql(data); | ||
expect(result.stats).to.eql({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
params: params, | ||
timeElapsed: gateway.timeElapsed, | ||
timeElapsedHumanized: Utils.humanizeTimeElapsed(gateway.timeElapsed) | ||
}); | ||
done(); | ||
}).catch(function(err) { | ||
done(err); | ||
}); | ||
gateway.successCallback(data); | ||
}); | ||
}); | ||
describe('when fail is called', function() { | ||
it('rejects with {request, err}', function(done) { | ||
var error1 = 'error1'; | ||
var error2 = 'error2'; | ||
gateway.promisify().then(function() { | ||
done(new Error('should have called "catch"')); | ||
}).catch(function(err) { | ||
try { | ||
expect(err.request).to.eql({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
params: params, | ||
}); | ||
expect(err.err).to.eql([error1, error2]); | ||
done(); | ||
} catch(e) { | ||
done(e); | ||
} | ||
}); | ||
gateway.failCallback(error1, error2); | ||
}); | ||
}); | ||
}); | ||
describe('#success', function() { | ||
@@ -187,12 +285,28 @@ var gateway, params; | ||
describe('#fail', 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, | ||
host: host, | ||
path: path, | ||
params: params, | ||
method: verb | ||
}); | ||
}); | ||
it('configures the failCallback', function() { | ||
var fail = function() {}; | ||
it('calls failCallback with requested resource object and errors', function() { | ||
var error1 = 'error1'; | ||
var error2 = 'error2'; | ||
var fail = sinon.spy(function() {}); | ||
gateway.fail(fail); | ||
expect(gateway.failCallback).to.equals(fail); | ||
gateway.failCallback(error1, error2); | ||
expect(fail).to.have.been.deep.calledWith({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
params: params, | ||
}, error1, error2); | ||
}); | ||
@@ -209,3 +323,8 @@ | ||
beforeEach(function() { | ||
gateway = new Gateway({url: url, method: verb}); | ||
gateway = new Gateway({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
method: verb | ||
}); | ||
}); | ||
@@ -229,3 +348,9 @@ | ||
beforeEach(function() { | ||
gateway = new Gateway({url: url, method: method, opts: {emulateHTTP: true}}); | ||
gateway = new Gateway({ | ||
url: url, | ||
host: host, | ||
path: path, | ||
method: method, | ||
opts: {emulateHTTP: true} | ||
}); | ||
}); | ||
@@ -232,0 +357,0 @@ |
@@ -47,2 +47,3 @@ var expect = chai.expect; | ||
test.gateway.prototype.call = function() {return this}; | ||
test.gateway.prototype.promisify = function() {return Promise.resolve(true)}; | ||
@@ -53,2 +54,3 @@ sinon.spy(test, 'gateway'); | ||
sinon.spy(test.gateway.prototype, 'call'); | ||
sinon.spy(test.gateway.prototype, 'promisify'); | ||
@@ -64,2 +66,3 @@ gateway = test.gateway; | ||
test.gateway.prototype.call.restore(); | ||
test.gateway.prototype.promisify.restore(); | ||
}); | ||
@@ -707,2 +710,35 @@ | ||
}); | ||
describe('with promises enabled', function() { | ||
var method, | ||
host, | ||
fullUrl, | ||
path, | ||
resolvedPath, | ||
params, | ||
callback; | ||
beforeEach(function() { | ||
Mappersmith.Env.USE_PROMISES = true; | ||
method = 'get'; | ||
host = mapper.resolveHost(); | ||
path = '/path'; | ||
resolvedPath = mapper.resolvePath(path, {a: true}); | ||
fullUrl = host + path; | ||
params = {a: true}; | ||
callback = Utils.noop; | ||
}); | ||
afterEach(function() { | ||
Mappersmith.Env.USE_PROMISES = false; | ||
}); | ||
it('calls promisify with callback to generate a promise', function() { | ||
var request = mapper.newGatewayRequest(method, path); | ||
request(params, callback); | ||
expect(gateway.prototype.promisify).to.have.been.calledWith(callback); | ||
}); | ||
}) | ||
}); |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
659629
42
17487
494
6