@lomray/react-mobx-manager
Version:
This package provides Mobx stores manager for react.
3 lines (2 loc) • 1.59 kB
JavaScript
import{makeExported as r}from"./make-exported.js";class s{promise;subqueries=new Map;store;params;constructor(s,{fieldName:e="sR",errorFields:t=["name","message"]}={}){this.store=s,this.params={fieldName:e,errorFields:t};const i=s.init?.bind(s);s.init=()=>{this.throwError(),i?.()},r(s,{[e]:"simple"})}errorJson(r){r.toJSON=()=>this.params.errorFields.reduce(((s,e)=>({...s,[e]:r?.[e]})),{})}jsonToError(r,s){return this.params.errorFields.forEach((e=>{r[e]=s?.[e]})),r}throwError(){const r=this.store[this.params.fieldName];if(r?.error)throw this.jsonToError(new Error(r?.error?.message??r?.error?.name),r?.error)}isComplete(r){const s=this.store[this.params.fieldName];return s?.error&&this.throwError(),!0===s?.done&&s.hash===r}query=(r,e={})=>{const{hash:t=""}=e,{fieldName:i}=this.params;if(!this.isComplete(t))return this.store[i]?.hash!==t&&(this.store[i]={hash:t,done:!1},this.promise=void 0),this.promise||(this.promise=r(),this.promise.then((()=>{this.store[i]={hash:t,done:!0}}),(r=>{this.errorJson(r),this.store[i]={error:r}}))),s.run(this.promise)};subquery=(r,e)=>{const{id:t,hash:i}=e,o=this.subqueries.get(t);if(!o)return void this.subqueries.set(t,{hash:i});if(o?.hash===i)return s.run(o?.promise);const h=r();return this.subqueries.set(t,{hash:i,promise:h}),s.run(h)};static run=r=>{if(r){switch(r.status){case"fulfilled":return r.value;case"pending":throw r;case"rejected":throw r.reason;default:r.status="pending",r.then((s=>{r.status="fulfilled",r.value=s}),(s=>{r.status="rejected",r.reason=s}))}throw r}}}export{s as default};
//# sourceMappingURL=suspense-query.js.map