UNPKG

rests

Version:

Easily generate API client's SDK — organize and simplify API Requests.

1 lines 7.96 kB
"use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function s(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}u((r=r.apply(e,t||[])).next())}))};function Rests(e,t){const n="undefined"!=typeof window?null===window||void 0===window?void 0:window.fetch:require("node-fetch"),r="undefined"!=typeof window?null===window||void 0===window?void 0:window.FormData:require("form-data");if(!n)throw new Error("Fetch API is not installed. If you are using Node please run `npm install node-fetch`");if(!r)throw new Error("FormData is not installed. If you are using Node please run `npm install form-data`");const o=e=>Object.assign(Object.assign({},e),{headers:Object.assign({},e.headers),params:Object.assign({},e.params),values:Object.assign({},e.values)}),i=e=>{var t,n;if("Object"!=(null===(n=null===(t=null==e?void 0:e.__proto__)||void 0===t?void 0:t.constructor)||void 0===n?void 0:n.name))throw new Error("Invalid $options object.");let r=o(e.$options||{});return delete e.$options,Object.assign(Object.assign({},r),{values:Object.assign(Object.assign({},r.values),e)})},a=(e,t,n=!1)=>{let r=n?e||{}:o(e||{}),i=o(t||{});return i.headers=Object.assign(Object.assign({},r.headers),i.headers),i.params=Object.assign(Object.assign({},r.params),i.params),i.values=Object.assign(Object.assign({},r.values),i.values),Object.assign(r,i),r};e=Object.assign({},e);let s={base:"",headers:{"User-Agent":"Rests JS (v1.1.1)"},params:{},values:{},on_error:void 0,on_success:void 0,on_request:void 0,fetch_agent:null};a(s,(null==e?void 0:e.$options)||{},!0),a(s,t,!0);const u={json:"application/json",form:"multipart/form-data",urlencoded:"application/x-www-form-urlencoded",text:"text/plain"},l=Object.values(u),d=["headers","body","query","path"],c={POST:"body",GET:"query"},f={"multipart/form-data":function(){var e=new r;return e.toString=function(){return this},e},"application/x-www-form-urlencoded":function(){return new URLSearchParams},"application/json":function(){return{append:function(e,t){this.data=this.data||{},this.data[e]=t},toString:function(){return JSON.stringify(this.data)},isEmpty:function(){return!this.data||0==Object.keys(this.data).length}}},"text/plain":function(){return{append:function(e,t){return this.data=this.data||[],this.data.push(t)},toString:function(){return this.data.join("")},isEmpty:function(){return!this.data||0==this.data.length}}}},h=e=>null==e,p=(...e)=>{for(var t=0;t<e.length;t++)if(null!==e[t]&&void 0!==e[t])return e[t];return null},v=(e,t,r,o)=>__awaiter(this,void 0,void 0,(function*(){return n(e,t).then((function(e){var t;return __awaiter(this,void 0,void 0,(function*(){try{var n=e.headers.get("Content-Type")||"";let i;try{i=e.type}catch(e){}let a={statusCode:e.status,statusText:e.statusText,headers:e.headers,type:i,ok:e.ok},s={"application/json":"json","text/plain":"text","(multipart/form-data|application/x-www-form-urlencoded)":"formData",blob:"blob",text:"text"},u=Object.keys(s).find((e=>new RegExp(e).test(n)))||"text";if(a[s[u]]=yield e[s[u]](),a.message=(null===(t=null==a?void 0:a.json)||void 0===t?void 0:t.message)||(e.ok?"Success.":"Something went wrong."),!e.ok)throw a;if(r.on_success){let e=r.on_success(a,o);if(void 0!==e)return e}return a}catch(e){if(r.on_error){let t=r.on_error(e,o);if(void 0!==t)return t}return Promise.reject(e)}}))}))}));function m(e,t,n){e.method=(e.method||"get").toUpperCase(),e.params=e.params||{};const r=function(o){var i,w,y,g,b,_;return __awaiter(this,void 0,void 0,(function*(){if(this instanceof r)throw new Error("This is an endpoint, you can't initialize this.");var j=a(s,t);j.on_request=e.on_request||j.on_request,j.on_success=e.on_success||j.on_success,j.on_error=e.on_error||j.on_error;var $=`${j.base}${e.path}`;((null==o?void 0:o.$sandbox)||(null===(i=null==j?void 0:j.values)||void 0===i?void 0:i.$sandbox))&&($=`${j.sandboxBase||j.base}${e.path}`);var O,x,E={method:e.method,headers:Object.assign({},j.headers),agent:j.fetch_agent},S=l.includes(e.enctype)?e.enctype:u[e.enctype||"json"],T=Object.assign({},j.params,e.params),R=f[S](),k=new URLSearchParams;for(var q in"FormData"==(null===(w=null==o?void 0:o.constructor)||void 0===w?void 0:w.name)?(O=o,o=Object.fromEntries(Array.from(O.keys(),(e=>e.endsWith("[]")?[e.slice(0,-2),O.getAll(e)]:[e,O.get(e)])))):o=o||{},T){var N=T[q],P=o[q],A=null===(y=null==j?void 0:j.values)||void 0===y?void 0:y[q],C=N.default,I=(null==o?void 0:o.$sandbox)||(null===(g=null==j?void 0:j.values)||void 0===g?void 0:g.$sandbox)?N.example:void 0,L=p(P,A,I,C),z=N.name||q,D=N.help||`The '${q}' field is invalid.`;if(N.required&&h(L))throw(F=new Error(D)).field=q,F;if(!h(L)){if("function"==typeof N.format)try{L=N.format(L)}catch(e){throw(F=new Error(e.message||D)).field=q,F}if(N.type&&"any"!==N.type)if((F=new Error(D)).field=q,["string","boolean","number"].includes(N.type)&&typeof L!=N.type||"array"==N.type&&!Array.isArray(L)||"object"==N.type&&(!L||"Object"!==L.__proto__.constructor.name))throw F;if(N.validate)if("RegExp"==(null===(_=null===(b=N.validate)||void 0===b?void 0:b.constructor)||void 0===_?void 0:_.name)&&(N.validate.toJSON=function(){return N.validate.toString().replace(/^\//g,"").replace(/\/$/g,"")}),!new RegExp(N.validate).test(L))throw(F=new Error(D)).field=q,F;if("number"==N.type){var F;if(N.hasOwnProperty("max")&&!isNaN(N.max)&&Number(L)>Number(N.max))throw(F=new Error(`The maximum allowed value allowed for the ${z} parameter is ${N.max}`)).field=q,F;if(N.hasOwnProperty("min")&&!isNaN(N.min)&&Number(L)<Number(N.min))throw(F=new Error(`The minimum allowed value allowed for the ${z} parameter is ${N.min}`)).field=q,F}if(N.in&&Array.isArray(N.in)&&!N.in.includes(L))throw(F=new Error(`The ${z} parameter should be one of these values: ${N.in}`)).field=q,F;var U="string"==typeof N.location?N.location.toLowerCase():c[E.method];if(!U||!d.includes(U))throw new Error(`Invalid location for '${q}' field.`);"headers"!=U?"body"!=U?"query"!=U?"path"==U&&($=$.replace(new RegExp(`{${(x=z,x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).trim()}}`),L)):k.append(z,L):R.append(z,L):(E.headers=E.headers||{},E.headers[z]=L)}}var J=k.toString();J&&($=`${$}?${J}`),R.keys&&(e=>{for(var t of e)return!1;return!0})(R.keys())||R.getLengthSync&&0==R.getLengthSync()||R.isEmpty&&R.isEmpty()||(E.body=R.toString()),E.body&&"multipart/form-data"!==S&&(E.headers=E.headers||{},E.headers["Content-Type"]=S);let B={url:$,options:E,params:o,key:n,instance:s.__$root_instance__,self:m(e,t,n)};if(j.on_request){var G=yield Promise.resolve(j.on_request(B));if(G){if(!(null==G?void 0:G.url)&&!(null==G?void 0:G.options))return G;$=G.url||$,E=G.options||E}if(!1===G)return!1}return v($,E,j,B)}))};return r}function w(t,n,r,o){var u={[t=t||"Rests"]:function(l){if(!(this instanceof u[t]))throw new Error("This is a category, you can initalize this category to update values using 'new' command.");if(o)throw new Error("This is already initialized, you can use 'set' instead.");let d=a(s,n),c=i(l),f=a(d,c);return Rests(r?(h=e,r.split(".").reduce(((e,t)=>null==e?void 0:e[t]),h)):e,f);var h}};return o&&(u[t].set=function(e){if(this instanceof u[t].set)throw new Error("The set object can't be initialized.");let n=i(e);return a(s,n,!0),u[t]}),u[t]}const y=Object.defineProperty(w("Rests",s,void 0,!0),"__schema__",{value:{schema:e,options:s},writable:!1,enumerable:!1});return s.__$root_instance__=y,function e(t,n,r,o){for(var i in n){var s=n[i];if(!s||"object"!=typeof s)continue;if(void 0!==t[i]){console.warn(`Skipping ${i} as it confilicts with another key in the object`);continue}let l=`${o?o+".":""}${i}`;if(s.hasOwnProperty("path")){var u=s;t[i]=m(u,r,l)}else{if("$"===i.substr(0,1))continue;let n=r;(null==s?void 0:s.$options)&&(n=a(r,null==s?void 0:s.$options)),t[i]=e(w(i,n,l),s,n,l)}}return t}(y,e,{})}Rests.default=Rests;