react-query-manager
Version:
This is a library to simplify the work with @tanstack/react-query. It offers unified style for keys in the cache, ability to cancel a request. automatic cache refresh after mutation.
2 lines • 17.9 kB
JavaScript
var U=class e extends Error{constructor(r,a,s){super(r);this.message=r;this.status=a;this.data=s;Object.setPrototypeOf(this,e.prototype),this.name=this.constructor.name,typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(r).stack,this.stack=new Error().stack,console.error(this.message,this)}};var ye=e=>{if(e!==null&&typeof e=="object"){let t={};return Object.entries(e).forEach(([a,s])=>{(s||typeof s=="boolean"||typeof s=="number")&&(t[a]=s)}),t}return{}},w=e=>encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]"),V=({onSuccess:e,onError:t,context:r,...a})=>{let s=a.data instanceof FormData,i=(()=>{let o=a.url;if(a.params){let c=ye(a.params);if(a.queryParamsSerializer)o+=`?${a.queryParamsSerializer(a.params)}`;else if(Object.keys(c).length>0){let y=[];for(let x in c)c.hasOwnProperty(x)&&(Array.isArray(c[x])?c[x].forEach(g=>{y.push(`${w(x)}${a.queryArrayParamStyle==="indexedArray"?"[]":""}=${w(g)}`)}):y.push(`${w(x)}=${w(c[x])}`));o+=`?${y.join("&")}`}}let[p,f]=o.split("?");return`${p}${f?`?${f}`:""}`})(),n=s?a.data:a.data?JSON.stringify(a.data):"",u={method:a.method,headers:{...!s&&{"Content-Type":"application/json"},...a.authorization&&{Authorization:a.authorization},...a.headers},...n&&{body:n},...a.options};return fetch(i,u).then(async o=>{let p=await(async()=>{try{let c=o.headers.get("Content-Length"),y=o.headers.get("Content-Type")?.toLowerCase();return o.status===204||o.status===304||c==="0"||!y?null:y.includes("application/json")?await o.json():y.includes("text/plain")||y.includes("text/csv")||y.includes("application/xml")||y.includes("text/xml")||y.includes("application/javascript")||y.includes("text/html")?await o.text():y.includes("multipart/form-data")?await o.formData():await o.blob()}catch{return null}})(),f={};return o.headers.forEach((c,y)=>{f[y]=c}),{status:o.status,statusText:o.statusText,headers:f,data:p}}).then(o=>{if(o.status<200||o.status>=300){let p=new U(`Request failed with status code: ${o.status}`,o.status,o.data);return t&&t(p,a,r),Promise.reject(p)}return e&&e(o,a,r),Promise.resolve(o)}).catch(o=>Promise.reject(new U(o.message)))};export*from"@tanstack/react-query";import{useQuery as Ee}from"@tanstack/react-query";function v(e){return typeof e=="string"?e.replace(/^\/+/,"").replace(/\/+$/,""):""}var R=(e,t)=>{let r=v(e.path.replace(/{(\w+)}/g,(a,s)=>e.params[s].toString()));return t?`${r}/`:r};import{QueryClient as De,QueryClientProvider as xe}from"@tanstack/react-query";import{ReactQueryDevtools as Qe}from"@tanstack/react-query-devtools";import{createContext as ge,useCallback as Y,useContext as Ce,useMemo as X}from"react";import{useCallback as ce}from"react";import{resolveValue as z,useToaster as pe}from"react-hot-toast/headless";import{jsx as I}from"react/jsx-runtime";var me=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"&&window.matchMedia){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})();function le({id:e,className:t,style:r,onHeightUpdate:a,children:s}){let i=ce(n=>{if(n){let u=()=>{let{height:o}=n.getBoundingClientRect();a(e,o)};u(),new MutationObserver(u).observe(n,{subtree:!0,childList:!0,characterData:!0})}},[e,a]);return I("div",{"data-toast-id":e,"data-testid":"toast-wrapper",ref:i,className:t,style:r,children:s})}var Te=(e,t)=>{let r=e.includes("top"),a=r?{top:0}:{bottom:0},s=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:me()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(r?1:-1)}px)`,...a,...s}},$=16;function G({reverseOrder:e,position:t="top-center",toastOptions:r,gutter:a,children:s,containerStyle:i,containerClassName:n}){let{toasts:u,handlers:o}=pe(r);return I("div",{style:{position:"fixed",zIndex:9999,top:$,left:$,right:$,bottom:$,pointerEvents:"none",...i},className:n,onMouseEnter:o.startPause,onMouseLeave:o.endPause,children:u.map(p=>{let f=p.position||t,c={...p,position:f},y=o.calculateOffset(c,{reverseOrder:e,gutter:a,defaultPosition:t}),x=Te(f,y),g=s;return I(le,{id:c.id,onHeightUpdate:o.updateHeight,style:{...x,pointerEvents:"auto"},children:c.type==="custom"?z(p.message,c):g?I(g,{...c}):I("div",{style:{display:p.visible?"flex":"none"},children:z(c.message,c)})},c.id)})})}import H from"react-hot-toast/headless";import{ToastBar as fe,resolveValue as de}from"react-hot-toast";var{remove:Ze,...he}=H,B=Object.assign((...e)=>H(...e),he),et=fe,tt=de;import Pe from"eventemitter3";var J=new Pe,S={once:(e,t)=>{J.once(e,t)},emit:(e,t)=>{J.emit(e,t)}};var L=process.env.NODE_ENV==="test";var _={queryClient:{}},C=()=>_.queryClient;import{Fragment as Re,jsx as j,jsxs as Z}from"react/jsx-runtime";var ee=ge({apiUrl:"",apiEnsureTrailingSlash:!1,apiClient:V,toastUndo:()=>{}}),E=()=>Ce(ee);function xt({children:e,config:t={},apiUrl:r,apiClient:a=V,apiEnsureTrailingSlash:s=!1,apiAuthorization:i,apiHeaders:n,apiOnSuccess:u,apiOnError:o,isDevTools:p,devToolsOptions:f,toast:c}){let y=X(()=>{let Q=new De({...t});return _.queryClient=Q,Q},[]),x=Y(Q=>{let m=i?i():"",l=n?n():{},h=(...d)=>{u&&u(...d),Q.onSuccess&&Q.onSuccess(...d)},T=(...d)=>{o&&o(...d),Q.onError&&Q.onError(...d)};return a({...Q,headers:Q.headers?{...l,...Q.headers}:l,authorization:Q.authorization||m,onSuccess:h,onError:T})},[]),g=Y(Q=>{let m=!1;B.dismiss();let l=()=>{m=!0,S.emit("end",!0),B.dismiss()};L||B.success(h=>{let T=c?.CustomUndoContent;return!h.visible&&!m&&(m=!0,S.emit("end",!1)),T?j(T,{message:Q.message,onUndo:l,type:Q.type,toast:h}):Z(Re,{children:[Q.message,j("span",{style:{marginLeft:"10px",cursor:"pointer"},onClick:l,role:"button",tabIndex:0,"aria-label":"Undo",title:"Undo",children:"UNDO"})]})},{duration:c?.globalProps?.toastOptions?.duration||5e3})},[]),K=X(()=>({apiUrl:v(r),apiClient:x,apiEnsureTrailingSlash:s,toastUndo:g}),[r,x,g,s]);return Z(xe,{client:y,children:[!L&&j(G,{...c?.globalProps,children:c?.CustomContent}),j(ee.Provider,{value:K,children:e}),p&&j(Qe,{buttonPosition:"bottom-right",initialIsOpen:!1,...f})]})}var bt=({queryOptions:e,resource:t,params:r={},apiClientParams:a})=>{let{apiUrl:s,apiClient:i,apiEnsureTrailingSlash:n}=E();return Ee({...e,queryKey:["get-list",t.path,t.params,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:o})=>{let p={resource:t,params:r,queryKey:o},f=`${s}/${R(p.resource,n)}`;return e?.queryFn?await e?.queryFn({apiClient:i,apiUrl:s,variables:p,url:f}):await i({url:f,method:"GET",params:r,...a})}})};import{useInfiniteQuery as be}from"@tanstack/react-query";var qt=({queryOptions:e,resource:t,params:r={},apiClientParams:a,pagination:s})=>{let{apiUrl:i,apiClient:n,apiEnsureTrailingSlash:u}=E();return be({initialPageParam:1,getNextPageParam:(...p)=>{let f=p[0],c=Number(p[2]);if(f?.data?.length)return c+1},getPreviousPageParam:(...p)=>{let f=Number(p[2]);if(!(f<=1))return f-1},...e,queryKey:["get-infinite-list",t.path,t.params,s,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:p,pageParam:f})=>{let c={resource:t,params:{...r,[s.page[0]]:f,[s.per_page[0]]:s.per_page[1]},queryKey:p},y=`${i}/${R(c.resource,u)}`;return e?.queryFn?await e?.queryFn({apiClient:n,apiUrl:i,variables:c,url:y}):await n({url:y,method:"GET",params:c.params,...a})}})};import{useQuery as Ke}from"@tanstack/react-query";var jt=({resource:e,id:t,queryOptions:r,params:a={},apiClientParams:s})=>{let{apiUrl:i,apiClient:n,apiEnsureTrailingSlash:u}=E();return Ke({...r,queryKey:["get-one",e.path,e.params,String(t),a,...r?.queryKey?r.queryKey:[]],queryFn:async({queryKey:p})=>{let f={id:t,resource:e,params:a,queryKey:p},c=`${i}/${R(f.resource,!0)}`;return r?.queryFn?await r?.queryFn({apiClient:n,apiUrl:i,variables:f,url:c}):await n({url:`${c}${f.id}${u?"/":""}`,method:"GET",params:a,...s})}})};import{useMutation as Me,useQueryClient as Se}from"@tanstack/react-query";import{useRef as Le}from"react";var te=({data:e,queryKeysOne:t})=>{let r=C();t&&t.forEach(a=>{r.setQueryData(a,e)})};var re=({data:e,queryKeysList:t,queryKeysInfiniteList:r,cacheAddItemTo:a="start"})=>{let s=C(),i=n=>!n||!(n.data instanceof Array)?n:{...n,data:a==="start"?[...e,...n.data]:[...n.data,...e]};t&&t.forEach(n=>{s.setQueriesData({queryKey:n},i)}),r&&r.forEach(n=>{s.setQueriesData({queryKey:n},u=>u&&{...u,pages:u.pages.map(i)})})};var ae=({queryKeys:e})=>{let t=C();e.forEach(r=>{t.removeQueries({queryKey:r})})};var se=({ids:e,queryKeysOne:t,queryKeysList:r,queryKeysInfiniteList:a})=>{let s=C(),i=n=>!n||!(n.data instanceof Array)?n:{...n,data:n.data.filter(u=>!e.some(o=>String(o)===String(u.id)))};t&&ae({queryKeys:t}),r&&r.forEach(n=>{s.setQueriesData({queryKey:n},i)}),a&&a.forEach(n=>{s.setQueriesData({queryKey:n},u=>u&&{...u,pages:u.pages.map(i)})})};var P={getOne:(e,t)=>["get-one",e.path,e.params,String(t)],getOneArray:(e,t)=>t.map(r=>["get-one",e.path,e.params,String(r)]),getList:e=>["get-list",e.path,e.params],getInfiniteList:e=>["get-infinite-list",e.path,e.params],getDataQuery:e=>["query-data",e.path,e.params]};function q(e,t){if(typeof e!=typeof t||Object.prototype.toString.call(e)!==Object.prototype.toString.call(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r]&&!q(e[r],t[r]))return!1;return!0}if(e instanceof Object&&t instanceof Object){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let s of r){let i=e[s],n=t[s];if(i!==n&&!q(i,n))return!1}return!0}return e===t}var Xt=({queryKeys:e})=>{C().invalidateQueries({predicate:r=>{let a=r.queryKey;return e.some(s=>s.every(i=>a.some(n=>q(n,i))))}})};var rr=({queryKeys:e})=>{C().removeQueries({predicate:r=>{let a=r.queryKey;return e.some(s=>s.every(i=>a.some(n=>q(n,i))))}})};var O=({queryKeys:e})=>{let t=C();e.forEach(r=>{t.invalidateQueries({queryKey:r})})};function oe(e){return["number","string"].includes(typeof e)}function Fe(e,t){return oe(e)&&oe(t)}function k(e,t){let r={...e};if(e instanceof Object&&t instanceof Object){for(let a in t)if(a in e){let s=e[a],i=t[a],n=typeof s==typeof i&&(Array.isArray(s)&&Array.isArray(i)||s!==null&&!Array.isArray(s)&&typeof s=="object"&&!Array.isArray(i)&&typeof i=="object"||typeof s!="object"&&typeof i!="object"),u=Fe(s,i);(n||u)&&(typeof s=="object"&&s!==null&&!Array.isArray(s)?r[a]=k(s,i):r[a]=i)}}return r}var ne=({data:e,ids:t,queryKeysOne:r,queryKeysList:a,queryKeysInfiniteList:s})=>{let i=C(),n=u=>!u||!(u.data instanceof Array)?u:{...u,data:u.data.map(o=>t.some(p=>String(p)===String(o.id))?k(o,e):o)};r&&r.forEach(u=>{i.setQueriesData({queryKey:u},o=>!o||!(o.data instanceof Object)||!(e instanceof Object)?o:{...o,data:k(o.data,e)})}),a&&a.forEach(u=>{i.setQueriesData({queryKey:u},n)}),s&&s.forEach(u=>{i.setQueriesData({queryKey:u},o=>o&&{...o,pages:o.pages.map(n)})})};var N=async e=>{let t=C(),r=e.reduce((a,s)=>a.concat(t.getQueriesData({queryKey:s})),[]);return await Promise.all(r.map(([a])=>t.cancelQueries({queryKey:a}))),r};var ie=({resourcePath:e,mutationOptions:t,mode:r={optimistic:!0,undoable:!0},extraResources:a=[],shouldUpdateCurrentResource:s=!0,shouldInvalidateCache:i=!0,type:n="many"})=>{let{apiUrl:u,apiClient:o,apiEnsureTrailingSlash:p,toastUndo:f}=E(),c=Se(),y=Le([]),x=()=>{y.current.forEach(([m,l])=>{c.setQueryData(m,l)})},{mutate:g,...K}=Me({...t,mutationKey:[n==="many"?"delete-many":"delete-one",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async m=>{let l=`${u}/${R(m.resource,!0)}`;if(t?.mutationFn)return await t?.mutationFn({apiClient:o,apiUrl:u,variables:m,url:l});let h=n==="many"?m.ids:[m.id],T=await Promise.allSettled(h.map(D=>o({url:`${l}${D}${p?"/":""}`,method:"DELETE",...m.apiClientParams}))),d=[];return T.forEach(D=>{if(D.status==="fulfilled")d.push(D.value);else throw D.reason}),n==="many"?d:d[0]},onSuccess:(...m)=>{if(i){let l=m[1],h=l.extraResources?[...a,...l.extraResources]:a,T=[P.getList(l.resource),P.getInfiniteList(l.resource)];h.forEach(d=>{T.push(P.getList(d)),T.push(P.getInfiniteList(d))}),O({queryKeys:T})}t?.onSuccess&&t.onSuccess(...m)},onError:(...m)=>{t?.onError&&t.onError(...m),x()}});return{mutation:K,delete:async({resourceParams:m,undoMessage:l,...h})=>{let T={path:e,params:m},d=n==="many"?h.ids:[h.id];if(r.optimistic){let D=h.extraResources?[...a,...h.extraResources]:a,b=s?P.getOneArray(T,d):[],F=s?[P.getList(T)]:[],M=s?[P.getInfiniteList(T)]:[];D.forEach(A=>{b.push(...P.getOneArray(A,d)),F.push(P.getList(A)),M.push(P.getInfiniteList(A))}),y.current=await N([...b,...F,...M]),se({ids:d,queryKeysOne:b,queryKeysList:F,queryKeysInfiniteList:M})}if(r.undoable&&!L){let D=d.length>1;S.once("end",b=>{b?x():g({...h,resource:T})}),f({message:l||`Element${D?"s":""} deleted`,type:D?"delete-many":"delete-one"})}else g({...h,resource:T})}}},Sr=e=>ie({...e,type:"one"}),Lr=e=>ie({...e,type:"many"});import{useMutation as qe,useQueryClient as Oe}from"@tanstack/react-query";import{useRef as Ae}from"react";var ue=({resourcePath:e,mutationOptions:t,mode:r={optimistic:!0,undoable:!0},extraResources:a=[],shouldUpdateCurrentResource:s=!0,shouldInvalidateCache:i=!0,type:n="many"})=>{let{apiUrl:u,apiClient:o,apiEnsureTrailingSlash:p,toastUndo:f}=E(),c=Oe(),y=Ae([]),x=()=>{y.current.forEach(([m,l])=>{c.setQueryData(m,l)})},{mutate:g,...K}=qe({...t,mutationKey:[n==="many"?"update-many":"update-one",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async m=>{let l=`${u}/${R(m.resource,!0)}`;if(t?.mutationFn)return await t?.mutationFn({apiClient:o,apiUrl:u,variables:m,url:l});let h=n==="many"?m.ids:[m.id],T=await Promise.allSettled(h.map(D=>o({url:`${l}${D}${p?"/":""}`,method:"PATCH",data:m.data,...m.apiClientParams}))),d=[];return T.forEach(D=>{if(D.status==="fulfilled")d.push(D.value);else throw D.reason}),n==="many"?d:d[0]},onSuccess:(...m)=>{if(i){let l=m[1],h=l.extraResources?[...a,...l.extraResources]:a,T=n==="many"?l.ids:[l.id],d=[...P.getOneArray(l.resource,T),P.getList(l.resource),P.getInfiniteList(l.resource)];h.forEach(D=>{d.push(...P.getOneArray(D,T)),d.push(P.getList(D)),d.push(P.getInfiniteList(D))}),O({queryKeys:d})}t?.onSuccess&&t.onSuccess(...m)},onError:(...m)=>{t?.onError&&t.onError(...m),x()}});return{mutation:K,update:async({resourceParams:m,undoMessage:l,...h})=>{let T={path:e,params:m},d=n==="many"?h.ids:[h.id];if(r.optimistic){let D=h.extraResources?[...a,...h.extraResources]:a,b=s?P.getOneArray(T,d):[],F=s?[P.getList(T)]:[],M=s?[P.getInfiniteList(T)]:[];D.forEach(W=>{b.push(...P.getOneArray(W,d)),F.push(P.getList(W)),M.push(P.getInfiniteList(W))}),y.current=await N([...b,...F,...M]);let A=h?.transformCacheData?h.transformCacheData(h.data):void 0;ne({data:A||h.data,ids:d,queryKeysOne:b,queryKeysList:F,queryKeysInfiniteList:M})}if(r.undoable&&!L){let D=d.length>1;S.once("end",b=>{b?x():g({...h,resource:T})}),f({message:l||`Element${D?"s":""} updated`,type:D?"update-many":"update-one"})}else g({...h,resource:T})}}},$r=e=>ue({...e,type:"one"}),Br=e=>ue({...e,type:"many"});import{useMutation as Ue}from"@tanstack/react-query";var Gr=({resourcePath:e,mutationOptions:t,extraResources:r=[],shouldUpdateCurrentResource:a=!0,cacheAddItemTo:s="start",shouldInvalidateCache:i=!0})=>{let{apiUrl:n,apiClient:u,apiEnsureTrailingSlash:o}=E(),{mutate:p,...f}=Ue({...t,mutationKey:["create",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async y=>{let x=`${n}/${R(y.resource,o)}`;return t?.mutationFn?await t?.mutationFn({apiClient:u,apiUrl:n,variables:y,url:x}):await u({url:x,method:"POST",data:y.data,...y.apiClientParams})},onSuccess:(...y)=>{let x=y[0],g=y[1],K=g.extraResources?[...r,...g.extraResources]:r;if(x){let Q=y[1],m=a?[P.getList(Q.resource)]:[],l=a?[P.getInfiniteList(Q.resource)]:[];K.forEach(T=>{m.push(P.getList(T)),l.push(P.getInfiniteList(T))});let h=Array.isArray(x)?x:[x];h.forEach(T=>{if(T){let{id:d}=T.data,D=a?[P.getOne(Q.resource,d)]:[];K.forEach(b=>{D.push(P.getOne(b,d))}),te({data:T,queryKeysOne:D.map(b=>[...b,{}])})}}),re({data:h.map(T=>T?.data||{}),cacheAddItemTo:s,queryKeysInfiniteList:l,queryKeysList:m}),i&&O({queryKeys:[...m,...l]})}t?.onSuccess&&t.onSuccess(...y)}});return{mutation:f,create:({resourceParams:y,...x})=>{p({...x,resource:{path:e,params:y}})}}};import{useQuery as Ie}from"@tanstack/react-query";var Zr=({queryOptions:e,resource:t,params:r={},apiClientParams:a})=>{let{apiUrl:s,apiClient:i,apiEnsureTrailingSlash:n}=E();return Ie({...e,queryKey:["query-data",t.path,t.params,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:o})=>{let p={resource:t,params:r,queryKey:o},f=`${s}/${R(p.resource,n)}`;return e?.queryFn?await e?.queryFn({apiClient:i,apiUrl:s,variables:p,url:f}):await i({url:f,method:"GET",params:r,...a})}})};import{useMutation as je}from"@tanstack/react-query";var sa=({resourcePath:e,mutationOptions:t})=>{let{apiUrl:r,apiClient:a,apiEnsureTrailingSlash:s}=E(),{mutate:i,...n}=je({...t,mutationKey:["mutate-data",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async o=>{let p=`${r}/${R(o.resource,s)}`;return t?.mutationFn?await t?.mutationFn({apiClient:a,apiUrl:r,variables:o,url:p}):await a({url:p,data:o.data,...o.apiClientParams})}});return{mutation:n,mutate:async({resourceParams:o,...p})=>{i({...p,resource:{path:e,params:o}})}}};export{U as CustomError,xt as RQWrapper,et as ToastBar,te as addItemToQueryCache,re as addItemsToListQueryCache,se as deleteItemsFromQueryCache,V as fetcher,R as getUrlFromResource,P as helpersQueryKeys,Xt as invalidateMatchingQueries,O as invalidateQueries,rr as removeMatchingQueries,ae as removeQueries,tt as resolveToastValue,B as toast,ne as updateItemsFromQueryCache,Gr as useCreate,sa as useDataMutate,Zr as useDataQuery,Lr as useDeleteMany,Sr as useDeleteOne,qt as useGetInfiniteList,bt as useGetList,jt as useGetOne,E as useRQWrapperContext,Br as useUpdateMany,$r as useUpdateOne};
//# sourceMappingURL=index.mjs.map