UNPKG

frest

Version:

REST client for browser with Fetch

19 lines (18 loc) 11.3 kB
/*! * frest 1.1.0 - https://github.com/panjiesw/frest * Copyright(c) Panjie Setiawan Wicaksono. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !function(){"use strict";function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function t(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function o(e,t){return(o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function i(e,t,r){return(i=s()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var s=new(Function.bind.apply(e,n));return r&&o(s,r.prototype),s}).apply(null,arguments)}function u(e){var t="function"==typeof Map?new Map:void 0;return(u=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return i(e,arguments,n(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),o(s,e)})(e)}var c=function(e){var t,r;function n(t,r,n,o){var s;return(s=e.call(this,t)||this).frest=r,s.request=n,s.response=o,s}return r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,o(t,r),n}(u(Error));function a(e,t){return new Promise((function(r,n){var o=new XMLHttpRequest;o.onload=function(){var e,n,s={headers:(e=o.getAllResponseHeaders()||"",n=new Headers,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var t=e.split(":"),r=t.shift().trim();if(r){var o=t.join(":").trim();n.append(r,o)}})),n),status:o.status,statusText:o.statusText};s.url="responseURL"in o?o.responseURL:s.headers.get("X-Request-URL");var i=t.responseType&&"text"!==t.responseType?o.response:o.responseText;r(new Response(i,s))},o.onerror=function(){n(new TypeError("Network request failed"))},o.ontimeout=function(){n(new TypeError("Network request failed"))},o.upload&&t.onUploadProgress&&(o.upload.onprogress=t.onUploadProgress),t.onDownloadProgress&&(o.onprogress=t.onDownloadProgress),o.open(t.method,e,!0),"include"===t.credentials&&(o.withCredentials=!0),o.responseType=t.responseType||"text","download"===t.action&&!t.responseType&&void 0!==FileReader&&void 0!==Blob&&function(){try{return new Blob,!0}catch(e){return!1}}()&&(o.responseType="blob"),t.headers.forEach((function(e,t){o.setRequestHeader(t,e)})),o.send(t.body)}))}var f=Object.prototype.hasOwnProperty;function p(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function h(e){try{return encodeURIComponent(e)}catch(e){return null}}for(var l={stringify:function(e,t){t=t||"";var r,n,o=[];for(n in"string"!=typeof t&&(t="?"),e)if(f.call(e,n)){if((r=e[n])||null!=r&&!isNaN(r)||(r=""),n=h(n),r=h(r),null===n||null===r)continue;o.push(n+"="+r)}return o.length?t+o.join("&"):""},parse:function(e){for(var t,r=/([^=?#&]+)=?([^&]*)/g,n={};t=r.exec(e);){var o=p(t[1]),s=p(t[2]);null===o||null===s||o in n||(n[o]=s)}return n}},d=Object.prototype.toString,y=function(e){return e.toString().replace(/([^:]\/)\/+/g,"$1")},g=function(e){return null!==e&&"object"==typeof e},v=function(e){return g(e)&&function(e){return"[object Function]"===d.call(e)}(e.pipe)},b=function(){function e(){this._int=[]}var r=e.prototype;return r.use=function(e){return this._int.push(e),this._int.length-1},r.eject=function(e){this._int.splice(e,1)},t(e,[{key:"handlers",get:function(){return this._int}}]),e}(),w=["fetch","base","method","headers"],m=["get","delete","options","download"],q=["post","put","patch","upload"],j=function(e,t){e.has("Content-Type")||e.set("Content-Type",t)},P=function(e,t){return void 0===t&&(t={}),{raw:e,data:t,headers:e.headers,ok:e.ok,redirected:e.redirected,status:e.status,statusText:e.statusText,trailer:e.trailer,type:e.type,url:e.url}},R=function(e,t){if(!e)throw new Error("one of interceptor didn't return "+("request"===t?t+" config":t))},O={base:"",fetch:fetch,headers:{common:new Headers({Accept:"application/json, text/plain, */*"}),post:new Headers,get:new Headers,put:new Headers,delete:new Headers,patch:new Headers,options:new Headers},method:"GET",transformResponse:[function(e){var t=e.headers.get("Content-Type");return t&&t.indexOf("application/json")>=0?e.clone().json().catch((function(t){return e.body})):e.body}],transformRequest:[function(e,t){var r,n=e.headers;return r=t,"undefined"!=typeof FormData&&r instanceof FormData||function(e){return"[object ArrayBuffer]"===d.call(e)}(t)||function(e){return null!=e&&null!=e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}(t)||v(t)||function(e){return"[object File]"===d.call(e)}(t)||function(e){return"[object Blob]"===d.call(e)}(t)?t:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}(t)?t.buffer:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}(t)?(j(n,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):g(t)?(j(n,"application/json;charset=utf-8"),JSON.stringify(t)):t}]},T=function(){function e(e){var t=this;if(this.config=void 0,this.interceptors={request:new b,response:new b,error:new b},this.req=function(e){var r;try{r=t.getFetch(e)}catch(e){return Promise.reject(e)}return r(t.parsePath(e.path,e.query),e).then((function(t){return{request:e,raw:t}}))},this.after=function(e){for(var r=e.raw,n=e.request,o=Promise.resolve({}),s=function(e){o=o.then((function(t){return n.transformResponse[e](r,t)}))},i=0;i<n.transformResponse.length;i++)s(i);if(!r.ok)return o.then((function(e){return Promise.reject(new c("Non OK HTTP response status: "+r.status+" - "+r.statusText,t,n,P(r,e)))}));for(var u=o.then((function(e){return P(r,e)})),a=function(e){u=u.then((function(r){return R(r,"response"),t.interceptors.response.handlers[e]({frest:t,request:n,response:r})}))},f=0;f<t.interceptors.response.handlers.length;f++)a(f);return u.then((function(e){return R(e,"response"),e})).catch((function(e){var o="string"==typeof e?e:e.message?e.message:e;return Promise.reject(new c("Error in response transform/interceptor: "+o,t,n,P(r)))}))},this.onError=function(e){return function(r){var n=t.toFrestError(r,e);return 0===t.interceptors.error.handlers.length?Promise.reject(n):new Promise((function(r,o){for(var s=Promise.resolve(null),i=null,u=function(r){if(null!=i)return"break";s=s.then((function(e){return null!=e?(i=e,e):t.interceptors.error.handlers[r](n)})).catch((function(r){return n=t.toFrestError(r,e),null}))},c=0;c<t.interceptors.error.handlers.length;c++){if("break"===u(c))break}s.then((function(e){e?r(e):o(n)}))}))}},e&&"string"==typeof e)this.config=r({},O,{base:e});else if(e&&"object"==typeof e){var n=r({},O.headers,e.headers);this.config=r({},O,e,{headers:n})}else this.config=r({},O);this.config.base=y(this.config.base)}var n=e.prototype;return n.create=function(t){return new e(t)},n.mergeConfig=function(e){var t=r({},this.config.headers,e.headers);this.config=r({},this.config,e,{headers:t})},n.parsePath=function(e,t){var r=e?e instanceof Array?e:[e]:[""];return t=this.parseQuery(t),y(this.config.base+"/"+r.map(encodeURI).join("/")+t)},n.parseQuery=function(e){return function(e){var t=e||"";return"object"==typeof t?t=l.stringify(t,"?"):""!==t&&(t="?"===t.charAt(0)?t:"?"+t),t}(e)},n.request=function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e,t){void 0===t&&(t={});var n=r({action:"request",method:this.config.method},this.requestConfig(e,t));return this.internalRequest(r({},n,{headers:this.headers(n)}))})),n.internalRequest=function(e){return this.before(e).then(this.req).then(this.after).catch(this.onError(e))},n.requestConfig=function(e,t){var n=this.config,o=(n.fetch,n.base,n.method,n.headers,function(e,t){if(null==e)return{};var r,n,o={},s=Object.keys(e);for(n=0;n<s.length;n++)r=s[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}(n,w));return"string"==typeof e||e instanceof Array?r({path:e},o,t):r({path:""},o,e)},n.headers=function(e){var t=e.method.toLowerCase(),r=new Headers(this.config.headers.common);return this.config.headers[t].forEach((function(e,t){r.set(t,e)})),e.headers&&e.headers.forEach((function(e,t){r.set(t,e)})),r},n.getFetch=function(e){if("upload"===e.action||"download"===e.action)return a;if("function"==typeof e.fetch)return e.fetch;if("function"==typeof this.config.fetch)return this.config.fetch;throw new c("Fetch API is not available in this browser",this,e)},n.before=function(e){var t=this;return new Promise((function(r,n){for(var o=Promise.resolve(e.body),s=function(t){q.indexOf(e.method.toLowerCase())>=0&&(o=o.then((function(r){return e.transformRequest[t](e,r)})))},i=0;i<e.transformRequest.length;i++)s(i);for(var u=o.then((function(t){return e.body=t,e})),a=function(e){u=u.then((function(r){return R(r,"request"),t.interceptors.request.handlers[e]({frest:t,request:r})}))},f=0;f<t.interceptors.request.handlers.length;f++)a(f);u.then((function(e){R(e,"request"),r(e)})).catch((function(r){var o="string"==typeof r?r:r.message?r.message:r;n(new c("Error in request transform/interceptor: "+o,t,e))}))}))},n.toFrestError=function(e,t){return function(e){return null!=e.frest&&null!=e.request}(e)?new c(e.message,this,t,e.response):e},t(e,[{key:"base",get:function(){return this.config.base}},{key:"fetchFn",get:function(){return this.config.fetch}}]),e}(),E=function(e){var t=m[e],n="download"===t?"GET":t.toUpperCase();T.prototype[t]=function(e,o){void 0===o&&(o={});var s=r({action:t,method:n},this.requestConfig(e,o));return this.internalRequest(r({},s,{headers:this.headers(s)}))}},x=0;x<m.length;x++)E(x);for(var F=function(e){var t=q[e],n="upload"===t?"POST":t.toUpperCase();T.prototype[t]=function(e,o,s){void 0===s&&(s={});var i=r({action:t,method:n},this.requestConfig(e,s));return this.internalRequest(r({body:o},i,{headers:this.headers(i)}))}},C=0;C<q.length;C++)F(C);self.frest=new T,self.Frest=T,self.FrestError=c}(); //# sourceMappingURL=frest.min.js.map