restglue
Version:
multi-api restful client (javascript) with glue, using superagent & promises (lightweight, no buildchain needed)
2 lines (1 loc) • 14.5 kB
JavaScript
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).superagent=t()}}(function(){return function t(e,r,n){function s(i,a){if(!r[i]){if(!e[i]){var u="function"==typeof require&&require;if(!a&&u)return u(i,!0);if(o)return o(i,!0);var h=new Error("Cannot find module '"+i+"'");throw h.code="MODULE_NOT_FOUND",h}var p=r[i]={exports:{}};e[i][0].call(p.exports,function(t){var r=e[i][1][t];return s(r||t)},p,p.exports,t,e,r,n)}return r[i].exports}for(var o="function"==typeof require&&require,i=0;i<n.length;i++)s(n[i]);return s}({1:[function(t,e,r){function n(t){if(t)return s(t)}function s(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}void 0!==e&&(e.exports=n),n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,s=0;s<r.length;s++)if((n=r[s])===e||n.fn===e){r.splice(s,1);break}return this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),r=this._callbacks["$"+t];if(r)for(var n=0,s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,e);return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},{}],2:[function(t,e,r){e.exports=function(t,e,r){for(var n=0,s=t.length,o=3==arguments.length?r:t[n++];n<s;)o=e.call(null,o,t[n],++n,t);return o}},{}],3:[function(t,e,r){function n(t){return null!=t&&"object"==typeof t}e.exports=n},{}],4:[function(t,e,r){var n=t("./is-object");r.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},r.parse=function(t){return this._parser=t,this},r.timeout=function(t){return this._timeout=t,this},r.then=function(t,e){return this.end(function(r,n){r?e(r):t(n)})},r.use=function(t){return t(this),this},r.get=function(t){return this._header[t.toLowerCase()]},r.getHeader=r.get,r.set=function(t,e){if(n(t)){for(var r in t)this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},r.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},r.field=function(t,e){return this._getFormData().append(t,e),this}},{"./is-object":3}],5:[function(t,e,r){function n(t,e,r){return"function"==typeof r?new t("GET",e).end(r):2==arguments.length?new t("GET",e):new t(e,r)}e.exports=n},{}],superagent:[function(t,e,r){function n(){}function s(t){switch({}.toString.call(t)){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}}function o(t){if(!v(t))return t;var e=[];for(var r in t)null!=t[r]&&i(e,r,t[r]);return e.join("&")}function i(t,e,r){if(Array.isArray(r))return r.forEach(function(r){i(t,e,r)});t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}function a(t){for(var e,r={},n=t.split("&"),s=0,o=n.length;s<o;++s)e=n[s].split("="),r[decodeURIComponent(e[0])]=decodeURIComponent(e[1]);return r}function u(t){var e,r,n,s,o=t.split(/\r?\n/),i={};o.pop();for(var a=0,u=o.length;a<u;++a)e=(r=o[a]).indexOf(":"),n=r.slice(0,e).toLowerCase(),s=x(r.slice(e+1)),i[n]=s;return i}function h(t){return/[\/+]json\b/.test(t)}function p(t){return t.split(/ *; */).shift()}function c(t){return b(t.split(/ *; */),function(t,e){var r=e.split(/ *= */),n=r.shift(),s=r.shift();return n&&s&&(t[n]=s),t},{})}function l(t,e){e=e||{},this.req=t,this.xhr=this.req.xhr,this.text="HEAD"!=this.req.method&&(""===this.xhr.responseType||"text"===this.xhr.responseType)||void 0===this.xhr.responseType?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText,this.setStatusProperties(this.xhr.status),this.header=this.headers=u(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this.setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this.parseBody(this.text?this.text:this.xhr.response):null}function f(t,e){var r=this;this._query=this._query||[],this.method=t,this.url=e,this.header={},this._header={},this.on("end",function(){var t=null,e=null;try{e=new l(r)}catch(e){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=e,t.rawResponse=r.xhr&&r.xhr.responseText?r.xhr.responseText:null,t.statusCode=r.xhr&&r.xhr.status?r.xhr.status:null,r.callback(t)}if(r.emit("response",e),t)return r.callback(t,e);if(e.status>=200&&e.status<300)return r.callback(t,e);var n=new Error(e.statusText||"Unsuccessful HTTP response");n.original=t,n.response=e,n.status=e.status,r.callback(n,e)})}function d(t,e){var r=w("DELETE",t);return e&&r.end(e),r}var y,m=t("emitter"),b=t("reduce"),g=t("./request-base"),v=t("./is-object");y="undefined"!=typeof window?window:"undefined"!=typeof self?self:this;var w=e.exports=t("./request").bind(null,f);w.getXHR=function(){if(!(!y.XMLHttpRequest||y.location&&"file:"==y.location.protocol&&y.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}return!1};var x="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};w.serializeObject=o,w.parseString=a,w.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},w.serialize={"application/x-www-form-urlencoded":o,"application/json":JSON.stringify},w.parse={"application/x-www-form-urlencoded":a,"application/json":JSON.parse},l.prototype.get=function(t){return this.header[t.toLowerCase()]},l.prototype.setHeaderProperties=function(t){var e=this.header["content-type"]||"";this.type=p(e);var r=c(e);for(var n in r)this[n]=r[n]},l.prototype.parseBody=function(t){var e=w.parse[this.type];return!e&&h(this.type)&&(e=w.parse["application/json"]),e&&t&&(t.length||t instanceof Object)?e(t):null},l.prototype.setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=(4==e||5==e)&&this.toError(),this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},l.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,n="cannot "+e+" "+r+" ("+this.status+")",s=new Error(n);return s.status=this.status,s.method=e,s.url=r,s},w.Response=l,m(f.prototype);for(var _ in g)f.prototype[_]=g[_];f.prototype.abort=function(){if(!this.aborted)return this.aborted=!0,this.xhr.abort(),this.clearTimeout(),this.emit("abort"),this},f.prototype.type=function(t){return this.set("Content-Type",w.types[t]||t),this},f.prototype.responseType=function(t){return this._responseType=t,this},f.prototype.accept=function(t){return this.set("Accept",w.types[t]||t),this},f.prototype.auth=function(t,e,r){switch(r||(r={type:"basic"}),r.type){case"basic":var n=btoa(t+":"+e);this.set("Authorization","Basic "+n);break;case"auto":this.username=t,this.password=e}return this},f.prototype.query=function(t){return"string"!=typeof t&&(t=o(t)),t&&this._query.push(t),this},f.prototype.attach=function(t,e,r){return this._getFormData().append(t,e,r||e.name),this},f.prototype._getFormData=function(){return this._formData||(this._formData=new y.FormData),this._formData},f.prototype.send=function(t){var e=v(t),r=this._header["content-type"];if(e&&v(this._data))for(var n in t)this._data[n]=t[n];else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"==r?this._data?this._data+"&"+t:t:(this._data||"")+t):this._data=t;return!e||s(t)?this:(r||this.type("json"),this)},l.prototype.parse=function(t){return y.console&&console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0"),this.serialize(t),this},l.prototype.serialize=function(t){return this._parser=t,this},f.prototype.callback=function(t,e){var r=this._callback;this.clearTimeout(),r(t,e)},f.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},f.prototype.timeoutError=function(){var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},f.prototype.withCredentials=function(){return this._withCredentials=!0,this},f.prototype.end=function(t){var e=this,r=this.xhr=w.getXHR(),o=this._query.join("&"),i=this._timeout,a=this._formData||this._data;this._callback=t||n,r.onreadystatechange=function(){if(4==r.readyState){var t;try{t=r.status}catch(e){t=0}if(0==t){if(e.timedout)return e.timeoutError();if(e.aborted)return;return e.crossDomainError()}e.emit("end")}};var u=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),t.direction="download",e.emit("progress",t)};this.hasListeners("progress")&&(r.onprogress=u);try{r.upload&&this.hasListeners("progress")&&(r.upload.onprogress=u)}catch(t){}if(i&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},i)),o&&(o=w.serializeObject(o),this.url+=~this.url.indexOf("?")?"&"+o:"?"+o),this.username&&this.password?r.open(this.method,this.url,!0,this.username,this.password):r.open(this.method,this.url,!0),this._withCredentials&&(r.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof a&&!s(a)){var p=this._header["content-type"],c=this._parser||w.serialize[p?p.split(";")[0]:""];!c&&h(p)&&(c=w.serialize["application/json"]),c&&(a=c(a))}for(var l in this.header)null!=this.header[l]&&r.setRequestHeader(l,this.header[l]);return this._responseType&&(r.responseType=this._responseType),this.emit("request",this),r.send(void 0!==a?a:null),this},w.Request=f,w.get=function(t,e,r){var n=w("GET",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},w.head=function(t,e,r){var n=w("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},w.del=d,w.delete=d,w.patch=function(t,e,r){var n=w("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},w.post=function(t,e,r){var n=w("POST",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},w.put=function(t,e,r){var n=w("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n}},{"./is-object":3,"./request":5,"./request-base":4,emitter:1,reduce:2}]},{},[])("superagent")});var nodejs="undefined"!=typeof module&&void 0!==module.exports,mapAsync=function(t,e,r){var n,s,o,i,a;s=[],o=0;for(i in t)a=t[i],n=function(t,n){return function(){var o;try{return r(n,t,s[t+1]||e)}catch(t){return o=t,e(new Error(o))}}},s.push(n(o++,a));return s[0]()},restglue=function(t){this.url=t||"",this.sandbox={},this.headers={},this.requestPre=[],this.requestPost=[]};if(restglue.prototype.beforeRequest=function(t){this.requestPre.push(t)},restglue.prototype.afterRequest=function(t){this.requestPost.push(t)},restglue.prototype.request=function(t,e,r,n,s){var o=this,i={method:t,url:e,query:n,payload:r,headers:s,api:this};n&&"string"==typeof n&&(i.url+=i.queryString=n),n&&"string"!=typeof n&&(i.url+=i.queryString="?"+o.toQueryString(n));for(var a in this.requestPre)this.requestPre[a](i);var u=this.getSandboxedUrl(i.method,i.url);if(u&&"string"!=typeof u)return u;e=u||i.url;var h=superagent[t](e);for(a in this.headers)h.set(a,this.headers[a]);for(a in s)h.set(a,s[a]);return"get"!=t&&h.send(r),new Promise(function(t,u){h.end(function(h,p){for(a in o.requestPost)o.requestPost[a](i,p,h);h?(nodejs||(console.error(h),console.error(JSON.stringify({url:e,payload:r,query:n,headers:s}))),u(h,p)):(nodejs||"#debug"!=document.location.hash||console.dir(p),p.body||(p.body={}),"string"!=typeof p.body&&"boolean"!=typeof p.body&&"integer"!=typeof p.body||(p.body={message:p.body}),p.body.getResponse=function(){return p},t(p.body))})})},restglue.prototype.toQueryString=function(t){var e=[];for(var r in t)e.push(r+"="+encodeURIComponent(t[r]));return e.join("&")},restglue.prototype.addEndpoint=function(t){var e=function(t,e){this.resourcename=t,this.api=e};e.prototype.getAll=function(t,e){return this.get(!1,t,e)},e.prototype.get=function(e,r,n){var s=this.api.url+"/"+t;return e&&(s+="/"+e),this.api.request("get",s,!1,r,n)},e.prototype.post=function(e,r,n){var s=this.api.url+"/"+t;return this.api.request("post",s,e,r,n)},["put","options","patch","delete"].map(function(r){e.prototype[r]=function(e,n,s,o){var i=this.api.url+"/"+t+"/"+e;return this.api.request(r,i,n,s,o)}}),this[t]=new e(t,this)},restglue.prototype.sandboxUrl=function(t,e){this.sandbox[t]=e},restglue.prototype.getSandboxedUrl=function(t,e){var r={method:t,url:e,payload:{},headers:this.headers,api:this};for(var n in this.sandbox){var s=this.sandbox[n],t=t.toUpperCase();if(null!=e.match(new RegExp(n,"g"))){if(s.path){var o="";o=(o=(o=e.replace(this.url,"")).replace(/\/?\?.*/,"")).replace(/\/[0-9]+/,"");var i=s.path+o+"/"+t.toLowerCase()+".json";return console.log("sandboxed url: "+t+" "+e+" => "+i),i}if(s.data){console.log("sandboxed url: "+t+" "+e+" => {}");var a={body:s.data};for(var u in this.requestPost)this.requestPost[u](r,a);return new Promise(function(t,e){t(a.body)})}}}return!1},restglue.prototype.compose=function(t){return function(){return new Promise(function(e,r){var n;mapAsync(t,function(){e(n)},function(t,e,r){var s=t(n),o=s;s.then||(s=new Promise(function(t,e){t(o)})),s.then(function(t){n=t,r()})})})}},nodejs){var superagent=require("superagent");module.exports=restglue}else window.restglue=restglue;