@nextgis/ngw-connector
Version:
A lightweight HTTP client optimized for use with NextGIS Web API
3 lines (2 loc) • 22.4 kB
JavaScript
import{isObject as e,objectRemoveEmpty as t,fixUrlStr as r,objectDeepEqual as n,defined as o}from"@nextgis/utils";import s from"@nextgis/cache";import{EventEmitter as i}from"events";const a=/\{ *([\w_-]+) *\}/g;function c(e,t){return e.replace(a,(e,r)=>{let n=t[r];if(void 0===n)throw new Error("No value provided for letiable "+e);return"function"==typeof n&&(n=n(t)),n})}var l=Object.defineProperty,u=Object.getOwnPropertySymbols,h=Object.prototype.hasOwnProperty,d=Object.prototype.propertyIsEnumerable,p=(e,t,r)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;function f(e){return t=this,r=null,n=function*(){const{params:t,name:r,connector:n,requestOptions:o}=e,s=yield n.connect();let i=s&&s[r];if(i){i=[...i];let e=i.shift();if(i.length){const r={};for(let e=0;e<i.length;e++){const n=i[e];if(r[e]=`{${n}}`,void 0===t[n])throw new Error(`\`${n}\` URL API argument is not specified`)}e&&(e=c(e,r))}if(t){const r=[],n=t.paramList;Array.isArray(n)&&n.forEach(([e,t])=>{r.push(`${e}=${t}`)});for(const e in t)-1===i.indexOf(e)&&r.push(`${e}=${t[e]}`);r.length&&(e=`${e}?${r.join("&")}`)}if(e)return n.makeQuery(e,t,((e,t)=>{for(var r in t||(t={}))h.call(t,r)&&p(e,r,t[r]);if(u)for(var r of u(t))d.call(t,r)&&p(e,r,t[r]);return e})({cacheName:r},o));throw new Error("Request URL is not set")}},new Promise((e,o)=>{var s=e=>{try{a(n.next(e))}catch(t){o(t)}},i=e=>{try{a(n.throw(e))}catch(t){o(t)}},a=t=>t.done?e(t.value):Promise.resolve(t.value).then(s,i);a((n=n.apply(t,r)).next())});var t,r,n}var y="3.0.1";class m extends Error{constructor(e="AbortError"){super(e),this.name="AbortError"}}var g=Object.defineProperty,b=(e,t,r)=>((e,t,r)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class w extends Error{constructor(e){super(),b(this,"name","NgwError"),b(this,"title"),b(this,"message"),b(this,"detail"),b(this,"exception"),b(this,"status_code"),b(this,"data"),b(this,"guru_meditation"),Object.assign(this,e),Object.setPrototypeOf(this,w.prototype)}}var v=Object.defineProperty,O=(e,t,r)=>((e,t,r)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class P extends w{constructor(e){super(e),O(this,"name","InsufficientPermissionsError"),O(this,"exception","nextgisweb.core.exception.InsufficientPermissions"),Object.setPrototypeOf(this,P.prototype)}}var j=Object.defineProperty,x=(e,t,r)=>((e,t,r)=>t in e?j(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let E=class e extends w{constructor(t){super(t),x(this,"message","There is no response from the server or problem connecting to server."),x(this,"title","Network error"),x(this,"detail","Check network connectivity and try again later."),Object.setPrototypeOf(this,e.prototype)}};var R=Object.defineProperty,C=(e,t,r)=>((e,t,r)=>t in e?R(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,t+"",r);class I extends Error{constructor(e){super(),C(this,"name","NetworkError"),Object.setPrototypeOf(this,I.prototype),this.message=`Unable to request ${e}.\n Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`}}var T=Object.defineProperty,_=(e,t,r)=>((e,t,r)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class k extends w{constructor(e){super(e),_(this,"name","ResourceNotFoundError"),_(this,"exception","nextgisweb.resource.exception.ResourceNotFound"),Object.setPrototypeOf(this,k.prototype)}}var q=Object.freeze({__proto__:null,AbortError:m,InsufficientPermissionsError:P,NetworkError:I,NetworksResponseError:E,NgwError:w,ResourceNotFoundError:k,extractError:function(t){if(e(t))return t.name&&t.message&&t.title?{title:t.title,message:t.message,detail:t.detail||null,data:t.data&&t.data.data?t.data.data:null}:!t.exception||void 0!==t.status&&0!==t.status&&void 0!==t.data?{title:"string"==typeof t.title?t.title:"Unexpected error",message:"string"==typeof t.message?t.message:"Something went wrong."}:new E({title:t.title,status_code:t.status_code,exception:t.exception})},isError:function(t){return!!e(t)&&(t.status_code&&t.exception&&t.title)}}),U=Object.defineProperty,$=(e,t,r)=>((e,t,r)=>t in e?U(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class A extends Error{constructor(e){super(e||"Something went wrong."),$(this,"title"),this.name="BaseAPIError",this.title="Unknown API error",Error.captureStackTrace&&Error.captureStackTrace(this,A)}}class N extends A{constructor(e){super(e||"There is no response from the server or problem connecting to server."),$(this,"detail"),this.title="Network error",this.detail="Check network connectivity and try again later."}}class S extends A{constructor(e){super(e||"Something went wrong."),this.title="Unexpected server response"}}class F extends A{constructor(e){super(e.message),$(this,"detail"),$(this,"data"),this.title=e.title||this.title,this.detail=e.detail||null,this.data=e}}class L extends Error{constructor(e,t={}){super(e||"Unexpected error while processing long-running request."),$(this,"title"),$(this,"data"),this.name="LunkwillError",this.title="Long-running request error",this.data=t,Error.captureStackTrace&&Error.captureStackTrace(this,L)}}class B extends L{constructor(e){super("Long-running request was cancelled.",e)}}class G extends L{constructor(e){super(void 0,e)}}var H=Object.defineProperty,D=Object.getOwnPropertySymbols,z=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable,Q=(e,t,r)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,J=(e,t)=>{for(var r in t||(t={}))z.call(t,r)&&Q(e,r,t[r]);if(D)for(var r of D(t))M.call(t,r)&&Q(e,r,t[r]);return e},W=(e,t,r)=>new Promise((n,o)=>{var s=e=>{try{a(r.next(e))}catch(t){o(t)}},i=e=>{try{a(r.throw(e))}catch(t){o(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,i);a((r=r.apply(e,t)).next())});function V(e){return W(this,null,function*(){const t=yield function(e){return W(this,null,function*(){try{return e.json()}catch(t){throw new Error}})}(e);let r=t.delay_ms;const n=void 0!==t.retry_ms?t.retry_ms:2e3,o=`/api/lunkwill/${t.id}/summary`,s=`/api/lunkwill/${t.id}/response`,i=e=>new Promise(t=>setTimeout(t,e));let a=!1,c=!1;for(;!c;){let e,t;yield i(a?n:r),a=!1;try{e=yield fetch(o,{credentials:"same-origin"}),t=yield e.json()}catch(l){a=!0;continue}switch(t.status){case void 0:throw new L(void 0,t);case"ready":c=!0;break;case"cancelled":throw new B(t);case"failed":throw new G(t);case"spooled":case"processing":case"buffering":r=t.delay_ms;break;default:throw new L(void 0,t)}}return s})}const K=new RegExp(["application/pdf","image/png","image/jpeg","image/tiff","text/csv"].join("|"));function X(e,t){let r="";return void 0!==t&&(r="?"+function(e){const t=[];for(const[r,n]of Object.entries(e))if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)t.push(`${r}=${encodeURIComponent(n)}`);else if(Array.isArray(n))t.push(`${r}=${n.map(encodeURIComponent).join(",")}`);else for(const[e,o]of Object.entries(n)){const n=`${r}[${encodeURIComponent(e)}]`;if("string"==typeof o||"number"==typeof o||"boolean"==typeof o)t.push(`${n}=${encodeURIComponent(o)}`);else if(Array.isArray(o)){const e=o.map(encodeURIComponent);t.push(`${n}=${e.join(",")}`)}}return t.join("&")}(t)),e+r}function Y(e,r,n){return W(this,null,function*(){var o,s;const i=J(J({},{method:"GET",credentials:"same-origin",headers:{}}),r),{withCredentials:a,responseType:c,cacheProps:l,cacheName:u,lunkwill:h,cache:d,query:p,json:f}=i,y=((e,t)=>{var r={};for(var n in e)z.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&D)for(var n of D(e))t.indexOf(n)<0&&M.call(e,n)&&(r[n]=e[n]);return r})(i,["withCredentials","responseType","cacheProps","cacheName","lunkwill","cache","query","json"]);y.method=null==(o=y.method)?void 0:o.toUpperCase(),a&&(y.credentials="include");let m=!1;void 0!==h&&(h.toHeaders(y.headers||{}),m=!0);const g=!!y.lunkwillReturnUrl;if(delete y.lunkwillReturnUrl,void 0!==f){y.body=JSON.stringify(f);const e=y.headers||{};e["Content-Type"]="application/json",y.headers=e}const b=X(e,p),w=()=>W(null,null,function*(){let e;try{e=yield fetch(b,y)}catch(o){if(y.signal&&y.signal.aborted)throw o;throw new N}if(m&&function(e){const t=e.headers.get("content-type");return null!=t&&t.includes("application/vnd.lunkwill.request-summary+json")}(e)){const t=yield V(e);if(g)return t;e=yield function(e){return W(this,null,function*(){try{return yield window.fetch(e,{credentials:"same-origin"})}catch(o){throw new N}})}(t)}const t=e.headers.get("content-type"),r=t&&(t.includes("application/json")||t.includes("application/vnd.lunkwill.request-summary+json"));let n;try{const o=t&&K.test(t);if("blob"===c||o)n=yield e.blob();else{if(!r)throw new S;n=yield e.json()}}catch(o){if("AbortError"===o.name||o instanceof S)throw o;throw new S}if(400<=e.status&&e.status<=599)throw new F(n);return n});if(n)if("GET"===(null==(s=y.method)?void 0:s.toUpperCase())){if(!1!==d){const e=l||J({},t({withCredentials:a,responseType:c}));return n.add(u||b,w,{props:e,expirationTime:d?void 0:500})}}else{["api/feature_layer/identify"].every(t=>!e.includes(t))&&n.clean()}return w()})}var Z=Object.defineProperty,ee=Object.defineProperties,te=Object.getOwnPropertyDescriptors,re=Object.getOwnPropertySymbols,ne=Object.prototype.hasOwnProperty,oe=Object.prototype.propertyIsEnumerable,se=(e,t,r)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ie=(e,t)=>{for(var r in t||(t={}))ne.call(t,r)&&se(e,r,t[r]);if(re)for(var r of re(t))oe.call(t,r)&&se(e,r,t[r]);return e},ae=(e,t)=>{var r={};for(var n in e)ne.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&re)for(var n of re(e))t.indexOf(n)<0&&oe.call(e,n)&&(r[n]=e[n]);return r};function ce(e,t,n,...o){const[s,...i]=n[e],a=o[0];let c;if(void 0===a)c=[];else if("object"==typeof a&&null!==a){if(o.length>1)throw new Error("Too many arguments for route(name, object)!");c=[];for(const[e,t]of Object.entries(a))c[i.indexOf(e)]=String(t)}else c=o.map(e=>String(e));return r(t+s.replace(/\{(\w+)\}/g,function(e,t){const r=parseInt(t),n=c[r];if(void 0===n){throw new Error(`Undefined parameter ${r} in "${s}".`)}return String(n)}))}function le(e,r,...n){const o={url:t=>{return o=null,s=null,i=function*(){var o;const s=yield r.connect();return X(ce(e,null!=(o=r.options.baseUrl)?o:"",s,...n),null==t?void 0:t.query)},new Promise((e,t)=>{var r=e=>{try{a(i.next(e))}catch(r){t(r)}},n=e=>{try{a(i.throw(e))}catch(r){t(r)}},a=t=>t.done?e(t.value):Promise.resolve(t.value).then(r,n);a((i=i.apply(o,s)).next())});var o,s,i}},s=["get","post","put","delete","patch"];for(const i of s){const s=o=>{var s;const a=o||{},{headers:c}=a,l=ae(a,["headers"]);if(null==(s=null==o?void 0:o.signal)?void 0:s.aborted)throw new m;return r.connect().then(o=>{var s;const a=ce(e,null!=(s=r.options.baseUrl)?s:"",o,...n),u=t(ie(ie({},r.getAuthorizationHeaders()),null!=c?c:{}));return Y(a,(h=ie({headers:u},l),ee(h,te({method:i}))),r.cache);var h})};o[i]=s}return o}function ue(e){return"[object Object]"===Object.prototype.toString.call(e)}let he;he=(e,t,r={},n,o)=>{r.method=r.method||"GET";const s=new XMLHttpRequest;s.open(r.method||"GET",e,!0),"blob"===r.responseType&&(s.responseType=r.responseType);const i=()=>{try{return JSON.parse(s.responseText)}catch(e){return s.responseText}};s.onload=()=>{-1!==[401,403,404,422,500].indexOf(s.status)&&n(new w(i())),((e=!1)=>{const o=e?n:t;"blob"===r.responseType?o(s.response):s.responseText?o(i()):n({message:""})})()},s.onerror=t=>{n(0===s.status?new I(e):t)},s.upload.onprogress=function(e){if(e.lengthComputable){r.onProgress&&r.onProgress(e.loaded/e.total*100,e)}};const a=r.headers;if(a)for(const l in a){const e=a[l];"string"==typeof e&&s.setRequestHeader(l,e)}let c;if(void 0!==r.withCredentials&&(s.withCredentials=r.withCredentials),r.file){if(c=new FormData,c.append("file",r.file),r.data)for(const l in r.data)c.append(l,c[l])}else c=r.data?"string"==typeof r.data?r.data:JSON.stringify(r.data):null;o&&o(()=>{s.abort()}),s.send(c)};const de=[];function pe(e){de.push(e)}var fe=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertySymbols,be=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable,ve=(e,t,r)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Oe=(e,t)=>{for(var r in t||(t={}))be.call(t,r)&&ve(e,r,t[r]);if(ge)for(var r of ge(t))we.call(t,r)&&ve(e,r,t[r]);return e},Pe=(e,t,r)=>ve(e,"symbol"!=typeof t?t+"":t,r),je=(e,t,r)=>new Promise((n,o)=>{var s=e=>{try{a(r.next(e))}catch(t){o(t)}},i=e=>{try{a(r.throw(e))}catch(t){o(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,i);a((r=r.apply(e,t)).next())});let xe=0,Ee=0;class Re{constructor(e){this.options=e,Pe(this,"id",xe++),Pe(this,"emitter",new i),Pe(this,"user"),Pe(this,"cache"),Pe(this,"withCredentials"),Pe(this,"routeCache"),Pe(this,"client",`NextGIS-NGW-Connector/${y}`),Pe(this,"routeStr","/api/component/pyramid/route"),Pe(this,"activeRequests",{}),Pe(this,"requestTransform");const t=function(e){return de.find(t=>{if(t.options.baseUrl===e.baseUrl){if(!e.auth)return!0;if(t.options.auth)return n(t.options.auth,e.auth)}})}(e);if(this.cache=new s({namespace:e.cacheId}),this.routeCache=new s({namespace:"routecache"}),t)return t;{const{route:e,requestTransform:t,withCredentials:r}=this.options;e&&(this.routeStr=e),t&&(this.requestTransform=t),void 0!==r&&(this.withCredentials=r),pe(this)}}clearCache(){this.cache.clean()}setRequestTransform(e){this.requestTransform=e}setNgw(e){this.logout(),this.options.baseUrl=e,pe(this)}connect(){return je(this,arguments,function*({signal:e}={}){const t=this.options.auth;if(t){const{login:e,password:r}=t;e&&r&&(yield this._login({login:e,password:r}))}const r=`${this.routeStr}?client=${this.client}`;return this.routeCache.add(this.options.baseUrl||String(this.id),()=>this.makeQuery(r,null,{signal:e,cache:!1}))})}login(e,t){return this.logout(),pe(this),this._login(e,t)}logout(){this.abort(),function(e){const t=de.indexOf(e);-1!==t&&de.splice(t,1)}(this),this.options.auth=void 0,this.user=void 0,this.routeCache.clean(),this.clearCache(),this.emitter.emit("logout")}getUserInfo(e,t){return je(this,null,function*(){if(this.user&&this.user.id)return this.user;e&&(this.options.auth=e);const r=Oe({headers:this.getAuthorizationHeaders(e),cache:!0},t);return this.makeQuery("/api/component/auth/current_user",{},r)})}getAuthorizationHeaders(e){const t=this.makeClientId(e);return t?{Authorization:`Basic ${t}`}:{}}makeClientId(e){if(e=e||this.options.auth){const{login:t,password:r}=e;return window.btoa(`${t}:${r}`)}}abort(){for(const e of Object.values(this.activeRequests))e.abort();this.activeRequests={}}getActiveApiRequests(){return Oe({},this.activeRequests)}route(e,...t){return le(e,this,...t)}makeQuery(e,n){return je(this,arguments,function*(e,n,o={}){var s;if(!(e=(this.options.baseUrl?this.options.baseUrl:"")+e))throw new Error("Empty `url` not allowed");if(n){const t=((e,t)=>{var r={};for(var n in e)be.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&ge)for(var n of ge(e))t.indexOf(n)<0&&we.call(e,n)&&(r[n]=e[n]);return r})(n,["paramList"]);e=c(e,t)}e=encodeURI(r(e)),o=Oe({withCredentials:this.withCredentials},o);const{cache:i,signal:a,method:l="GET",headers:u,cacheName:h,cacheProps:d,responseType:p,withCredentials:f}=o,y=new AbortController,g=y.signal;if(a){if(a.aborted)throw new m;a.addEventListener("abort",()=>{y.abort()})}o.signal=g;const b=()=>je(this,null,function*(){const t=Ee++;this.activeRequests[t]=y;try{return this._loadData(e,o)}finally{this._cleanActiveRequest(t)}});if("GET"===l&&!1!==i){const r=d||(w=Oe({},t({headers:u,withCredentials:f,responseType:p,baseUrl:this.options.baseUrl,userId:null==(s=this.user)?void 0:s.id})),ye(w,me({params:n})));return this.cache.add(h||e,b,{props:r,expirationTime:i?void 0:500})}var w;return b()})}_loadData(e,t){return t.responseType=t.responseType||"json",new Promise((r,n)=>{var o;if(this.user&&((t=t||{}).headers=Oe(Oe({},this.getAuthorizationHeaders()),t.headers)),this.requestTransform){const[r,n]=this.requestTransform(e,t);e=r,t=n}let s;he(e,r,t,n,e=>{s=e}),null==(o=t.signal)||o.addEventListener("abort",()=>{void 0!==s&&s(),n(new m)})}).catch(e=>{if("AbortError"!==e.name){"production"!==process.env.NODE_ENV&&console.warn("DEV WARN",e);const t=this._handleHttpError(e);if(t)throw t}throw e})}_login(e,t){return je(this,null,function*(){try{const r=yield this.getUserInfo(e,t);return this.user=r,this.emitter.emit("login",r),r}catch(r){throw this.emitter.emit("login:error",r),r}})}_cleanActiveRequest(e){delete this.activeRequests[e]}_handleHttpError(e){if(e&&e instanceof w){if("nextgisweb.resource.exception.ResourceNotFound"===e.exception)throw new k(e);if("nextgisweb.core.exception.InsufficientPermissions"===e.exception)throw new P(e)}return e}}Pe(Re,"errors",q);const Ce=["description"];function Ie(e,t=""){t=t?t+"__":"";const r={};for(const[n,s]of Object.entries(e))if(-1===Ce.indexOf(n))if(ue(s))if("owner_user"===n){const e=Ie(s,n);Object.assign(r,e)}else"parent"===n&&"id"in s&&(r.parent_id=s.id);else o(s)&&(r[t+n]=s);return r}var Te=Object.defineProperty,_e=Object.defineProperties,ke=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertySymbols,Ue=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable,Ae=(e,t,r)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ne=(e,t)=>{for(var r in t||(t={}))Ue.call(t,r)&&Ae(e,r,t[r]);if(qe)for(var r of qe(t))$e.call(t,r)&&Ae(e,r,t[r]);return e},Se=(e,t)=>_e(e,ke(t)),Fe=(e,t,r)=>Ae(e,"symbol"!=typeof t?t+"":t,r),Le=(e,t,r)=>new Promise((n,o)=>{var s=e=>{try{a(r.next(e))}catch(t){o(t)}},i=e=>{try{a(r.throw(e))}catch(t){o(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,i);a((r=r.apply(e,t)).next())});class Be{constructor({connector:e,cacheId:t}){Fe(this,"cache"),Fe(this,"connector"),this.connector=e,this.cache=new s({namespace:t})}getOne(e,t){const r=Ne({},t);return"string"==typeof e||"number"==typeof e||ue(e),"string"==typeof e?this._fetchResourceBy({keyname:e},r):"number"==typeof e?this._fetchResourceById(e,r):ue(e)?this._fetchResourceBy(e,r):Promise.resolve(void 0)}getOneOrFail(e,t){return this.getOne(e,t).then(e=>{if(e)return e;throw new k})}getId(e,t){return"number"==typeof e?Promise.resolve(e):"string"==typeof e||ue(e)?this.getOne(e,t).then(e=>{if(e)return e.resource.id}):Promise.resolve(void 0)}getIdOrFail(e,t){return this.getId(e,t).then(e=>{if(void 0===e)throw new Error;return e})}getMany(e,t){return this._resourceCacheFilter(e).then(r=>{if(!r.length){const r={};return e.keyname?r.keyname=e.keyname:Object.assign(r,Ie(e)),this.connector.route("resource.search").get(Se(Ne({},t),{query:Ne({serialization:"full"},r)})).then(e=>{if((null==t?void 0:t.cache)&&e)for(const t of e)this.cache.add("resource.item",Promise.resolve(t),{id:t.resource.id});return e})}return r})}getParent(e,t){return this.getOne(e,t).then(e=>{var r,n;return(null==(n=null==(r=null==e?void 0:e.resource)?void 0:r.parent)?void 0:n.id)?this.getOne(e.resource.parent.id,t):Promise.resolve(void 0)})}getChildrenOf(e,t){return this.getIdOrFail(e).then(e=>this._getChildrenOf(e,t))}update(e,t){return this.getId(e).then(e=>{if(void 0!==e)return this.connector.put("resource.item",{data:t},{id:e})})}delete(e){return this.getId(e).then(e=>{if(void 0!==e)return this.connector.delete("resource.item",null,{id:e}).then(()=>{this._cleanResourceItemCache(e)})})}_getChildrenOf(e,t){return Le(this,arguments,function*(e,t,r=[]){let n;n="string"==typeof e?yield this.getId(e,t):"object"==typeof e?e.id:e;const o=yield this.connector.route("resource.collection").get(Se(Ne({},t),{query:{parent:n}})),s=[];for(const i of o)(null==t?void 0:t.cache)&&this.cache.add("resource.item",Promise.resolve(i),{id:i.resource.id}),r.push(i),(null==t?void 0:t.recursive)&&i.resource.children&&s.push(this._getChildrenOf(i.resource.id,t,r));return s.length?Promise.all(s).then(()=>r):r})}_cleanResourceItemCache(e){return Le(this,null,function*(){var t;const r=this.cache.all(),n=[];for(const o of r){const r=null==(t=o.props)?void 0:t.id;if(["resource.item","resource"].includes(o.key)&&void 0!==r)if("number"==typeof r)r===e&&n.push(o);else{(yield this.getId(r))===e&&n.push(o)}}for(const e of n)this.cache.delete(e)})}_fetchResourceById(e,t){return this.connector.route("resource.item",{id:e}).get(t)}_fetchResourceBy(e,t){return this.getMany(e,t).then(e=>e[0])}_resourceCacheFilter(e){return Promise.all(this.cache.matchAll("resource.item")).then(t=>(t.filter(t=>{if(t)return e.keyname&&t.resource.keyname?e.keyname===t.resource.keyname:o(e.id)&&o(t.resource.id)?e.id===t.resource.id:n(e,t.resource)}),[]))}}var Ge=Object.defineProperty,He=(e,t,r)=>((e,t,r)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,t+"",r);class De extends Re{constructor(e){super(e),He(this,"resources"),this.resources=new Be({connector:this,cacheId:e.cacheId})}static create(e){return new this(e)}clearCache(){super.clearCache(),this.resources.cache.clean()}apiRequest(e,r={},n={}){var o;r=null!=(o=n.params)?o:r;return f({name:e,params:t(r),requestOptions:n,connector:this})}post(e,t,r){return(t=t||{}).method="POST",this.apiRequest(e,r,t)}get(e,t,r){return(t=t||{}).method="GET",this.apiRequest(e,r,t)}patch(e,t,r){return(t=t||{}).method="PATCH",this.apiRequest(e,r,t)}put(e,t,r){return(t=t||{}).method="PUT",this.apiRequest(e,r,t)}delete(e,t,r){return(t=t||{}).method="DELETE",this.apiRequest(e,r,t)}getResource(e,t){return this.resources.getOne(e,t)}getResourceOrFail(e,t){return this.resources.getOneOrFail(e,t)}getResourceBy(e){return this.resources.getOne(e)}getResourceByKeyname(e){return this.resources.getOne(e)}getResourceById(e){return this.resources.getOne(e)}getResourceId(e,t){return this.resources.getId(e,t)}getResourceIdOrFail(e,t){return this.resources.getIdOrFail(e,t)}getResourcesBy(e,t){return this.resources.getMany(e,t)}getResourceParent(e,t){return this.resources.getParent(e,t)}getResourceChildren(e,t){return this.resources.getChildrenOf(e,t)}updateResource(e,t){return this.resources.update(e,t)}deleteResource(e){return this.resources.delete(e)}}export{De as default};
//# sourceMappingURL=ngw-connector.esm-bundler.prod.js.map