UNPKG

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 18.2 kB
var U=class e extends Error{constructor(r,a,o){super(r);this.message=r;this.status=a;this.data=o;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,o])=>{(o||typeof o=="boolean"||typeof o=="number")&&(t[a]=o)}),t}return{}},v=e=>encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]"),j=({onSuccess:e,onError:t,context:r,...a})=>{let o=a.data instanceof FormData,i=(()=>{let n=a.url;if(a.params){let c=ye(a.params);if(a.queryParamsSerializer)n+=`?${a.queryParamsSerializer(a.params)}`;else if(Object.keys(c).length>0){let m=[];for(let x in c)c.hasOwnProperty(x)&&(Array.isArray(c[x])?c[x].forEach(g=>{m.push(`${v(x)}${a.queryArrayParamStyle==="indexedArray"?"[]":""}=${v(g)}`)}):m.push(`${v(x)}=${v(c[x])}`));n+=`?${m.join("&")}`}}let[u,y]=n.split("?");return`${u}${y?`?${y}`:""}`})(),s=o?a.data:a.data?JSON.stringify(a.data):"",p={method:a.method,headers:{...!o&&{"Content-Type":"application/json"},...a.authorization&&{Authorization:a.authorization},...a.headers},...s&&{body:s},...a.options};return fetch(i,p).then(async n=>{let u=await(async()=>{try{let c=n.headers.get("Content-Length"),m=n.headers.get("Content-Type")?.toLowerCase();return n.status===204||n.status===304||c==="0"||!m?null:m.includes("application/json")?await n.json():m.includes("text/plain")||m.includes("text/csv")||m.includes("application/xml")||m.includes("text/xml")||m.includes("application/javascript")||m.includes("text/html")?await n.text():m.includes("multipart/form-data")?await n.formData():await n.blob()}catch{return null}})(),y={};return n.headers.forEach((c,m)=>{y[m]=c}),{status:n.status,statusText:n.statusText,headers:y,data:u}}).then(n=>{if(n.status<200||n.status>=300){let u=new U(`Request failed with status code: ${n.status}`,n.status,n.data);return t&&t(u,a,r),Promise.reject(u)}return e&&e(n,a,r),Promise.resolve(n)}).catch(n=>Promise.reject(new U(n.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,o)=>e.params[o].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:o}){let i=ce(s=>{if(s){let p=()=>{let{height:n}=s.getBoundingClientRect();a(e,n)};p(),new MutationObserver(p).observe(s,{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:o})}var Te=(e,t)=>{let r=e.includes("top"),a=r?{top:0}:{bottom:0},o=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,...o}},$=16;function G({reverseOrder:e,position:t="top-center",toastOptions:r,gutter:a,children:o,containerStyle:i,containerClassName:s}){let{toasts:p,handlers:n}=pe(r);return I("div",{style:{position:"fixed",zIndex:9999,top:$,left:$,right:$,bottom:$,pointerEvents:"none",...i},className:s,onMouseEnter:n.startPause,onMouseLeave:n.endPause,children:p.map(u=>{let y=u.position||t,c={...u,position:y},m=n.calculateOffset(c,{reverseOrder:e,gutter:a,defaultPosition:t}),x=Te(y,m),g=o;return I(le,{id:c.id,onHeightUpdate:n.updateHeight,style:{...x,pointerEvents:"auto"},children:c.type==="custom"?z(u.message,c):g?I(g,{...c}):I("div",{style:{display:u.visible?"flex":"none"},children:z(c.message,c)})},c.id)})})}import H from"react-hot-toast/headless";import{ToastBar as fe,resolveValue as he}from"react-hot-toast";var{remove:Ze,...de}=H,B=Object.assign((...e)=>H(...e),de),et=fe,tt=he;import Pe from"eventemitter3";var J=new Pe,O={once:(e,t)=>{J.once(e,t)},emit:(e,t)=>{J.emit(e,t)}};var S=process.env.NODE_ENV==="test";var _={queryClient:{}},C=()=>_.queryClient;import{Fragment as Re,jsx as w,jsxs as Z}from"react/jsx-runtime";var ee=ge({apiUrl:"",apiEnsureTrailingSlash:!1,apiClient:j,toastUndo:()=>{}}),E=()=>Ce(ee);function xt({children:e,config:t={},apiUrl:r,apiClient:a=j,apiEnsureTrailingSlash:o=!1,apiAuthorization:i,apiHeaders:s,apiOnSuccess:p,apiOnError:n,isDevTools:u,devToolsOptions:y,toast:c}){let m=X(()=>{let Q=new De({...t});return _.queryClient=Q,Q},[]),x=Y(Q=>{let l=i?i():"",T=s?s():{},h=(...d)=>{p&&p(...d),Q.onSuccess&&Q.onSuccess(...d)},f=(...d)=>{n&&n(...d),Q.onError&&Q.onError(...d)};return a({...Q,headers:Q.headers?{...T,...Q.headers}:T,authorization:Q.authorization||l,onSuccess:h,onError:f})},[]),g=Y(Q=>{let l=!1;B.dismiss();let T=()=>{l=!0,O.emit("end",!0),B.dismiss()};S||B.success(h=>{let f=c?.CustomUndoContent;return!h.visible&&!l&&(l=!0,O.emit("end",!1)),f?w(f,{message:Q.message,onUndo:T,type:Q.type,toast:h}):Z(Re,{children:[Q.message,w("span",{style:{marginLeft:"10px",cursor:"pointer"},onClick:T,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:o,toastUndo:g}),[r,x,g,o]);return Z(xe,{client:m,children:[!S&&w(G,{...c?.globalProps,children:c?.CustomContent}),w(ee.Provider,{value:K,children:e}),u&&w(Qe,{buttonPosition:"bottom-right",initialIsOpen:!1,...y})]})}var bt=({queryOptions:e,resource:t,params:r={},apiClientParams:a})=>{let{apiUrl:o,apiClient:i,apiEnsureTrailingSlash:s}=E();return Ee({...e,queryKey:["get-list",t.path,t.params,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:n})=>{let u={resource:t,params:r,queryKey:n},y=`${o}/${R(u.resource,s)}`;return e?.queryFn?await e?.queryFn({apiClient:i,apiUrl:o,variables:u,url:y}):await i({url:y,method:"GET",params:r,...a})}})};import{useInfiniteQuery as be}from"@tanstack/react-query";var Lt=({queryOptions:e,resource:t,params:r={},apiClientParams:a,pagination:o})=>{let{apiUrl:i,apiClient:s,apiEnsureTrailingSlash:p}=E();return be({initialPageParam:1,getNextPageParam:(...u)=>{let y=u[0],c=Number(u[2]);if(y?.data?.length)return c+1},getPreviousPageParam:(...u)=>{let y=Number(u[2]);if(!(y<=1))return y-1},...e,queryKey:["get-infinite-list",t.path,t.params,o,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:u,pageParam:y})=>{let c={resource:t,params:{...r,[o.page[0]]:y,[o.per_page[0]]:o.per_page[1]},queryKey:u},m=`${i}/${R(c.resource,p)}`;return e?.queryFn?await e?.queryFn({apiClient:s,apiUrl:i,variables:c,url:m}):await s({url:m,method:"GET",params:c.params,...a})}})};import{useQuery as Ke}from"@tanstack/react-query";var wt=({resource:e,id:t,queryOptions:r,params:a={},apiClientParams:o})=>{let{apiUrl:i,apiClient:s,apiEnsureTrailingSlash:p}=E();return Ke({...r,queryKey:["get-one",e.path,e.params,String(t),a,...r?.queryKey?r.queryKey:[]],queryFn:async({queryKey:u})=>{let y={id:t,resource:e,params:a,queryKey:u},c=`${i}/${R(y.resource,!0)}`;return r?.queryFn?await r?.queryFn({apiClient:s,apiUrl:i,variables:y,url:c}):await s({url:`${c}${y.id}${p?"/":""}`,method:"GET",params:a,...o})}})};import{useMutation as Fe,useQueryClient as Oe}from"@tanstack/react-query";import{useRef as Se}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 o=C(),i=s=>!s||!(s.data instanceof Array)?s:{...s,data:a==="start"?[...e,...s.data]:[...s.data,...e]};t&&t.forEach(s=>{o.setQueriesData({queryKey:s},i)}),r&&r.forEach(s=>{o.setQueriesData({queryKey:s},p=>p&&{...p,pages:p.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 o=C(),i=s=>!s||!(s.data instanceof Array)?s:{...s,data:s.data.filter(p=>!e.some(n=>String(n)===String(p.id)))};t&&ae({queryKeys:t}),r&&r.forEach(s=>{o.setQueriesData({queryKey:s},i)}),a&&a.forEach(s=>{o.setQueriesData({queryKey:s},p=>p&&{...p,pages:p.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 L(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]&&!L(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 o of r){let i=e[o],s=t[o];if(i!==s&&!L(i,s))return!1}return!0}return e===t}var Xt=({queryKeys:e})=>{C().invalidateQueries({predicate:r=>{let a=r.queryKey;return e.some(o=>o.every(i=>a.some(s=>L(s,i))))}})};var rr=({queryKeys:e})=>{C().removeQueries({predicate:r=>{let a=r.queryKey;return e.some(o=>o.every(i=>a.some(s=>L(s,i))))}})};var q=({queryKeys:e})=>{let t=C();e.forEach(r=>{t.invalidateQueries({queryKey:r})})};function oe(e){return["number","string"].includes(typeof e)}function Me(e,t){return oe(e)&&oe(t)}function k(e,t,r){let a={...e};if(e instanceof Object&&t instanceof Object){for(let o in t)if(o in e){let i=e[o],s=t[o],p=typeof i==typeof s&&(Array.isArray(i)&&Array.isArray(s)||i!==null&&!Array.isArray(i)&&typeof i=="object"&&!Array.isArray(s)&&typeof s=="object"||typeof i!="object"&&typeof s!="object"),n=Me(i,s);(p||n||r?.overwriteOnTypeMismatch||r?.overwriteOnTypeMismatchKeys?.includes(o))&&(typeof i=="object"&&i!==null&&!Array.isArray(i)?a[o]=k(i,s):a[o]=s)}}return a}var ne=({data:e,ids:t,queryKeysOne:r,queryKeysList:a,queryKeysInfiniteList:o,overwriteOnTypeMismatch:i,overwriteOnTypeMismatchKeys:s})=>{let p=C(),n=u=>!u||!(u.data instanceof Array)?u:{...u,data:u.data.map(y=>t.some(c=>String(c)===String(y.id))?k(y,e,{overwriteOnTypeMismatch:i,overwriteOnTypeMismatchKeys:s}):y)};r&&r.forEach(u=>{p.setQueriesData({queryKey:u},y=>!y||!(y.data instanceof Object)||!(e instanceof Object)?y:{...y,data:k(y.data,e,{overwriteOnTypeMismatch:i,overwriteOnTypeMismatchKeys:s})})}),a&&a.forEach(u=>{p.setQueriesData({queryKey:u},n)}),o&&o.forEach(u=>{p.setQueriesData({queryKey:u},y=>y&&{...y,pages:y.pages.map(n)})})};var N=async e=>{let t=C(),r=e.reduce((a,o)=>a.concat(t.getQueriesData({queryKey:o})),[]);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:o=!0,shouldInvalidateCache:i=!0,type:s="many"})=>{let{apiUrl:p,apiClient:n,apiEnsureTrailingSlash:u,toastUndo:y}=E(),c=Oe(),m=Se([]),x=()=>{m.current.forEach(([l,T])=>{c.setQueryData(l,T)})},{mutate:g,...K}=Fe({...t,mutationKey:[s==="many"?"delete-many":"delete-one",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async l=>{let T=`${p}/${R(l.resource,!0)}`;if(t?.mutationFn)return await t?.mutationFn({apiClient:n,apiUrl:p,variables:l,url:T});let h=s==="many"?l.ids:[l.id],f=await Promise.allSettled(h.map(D=>n({url:`${T}${D}${u?"/":""}`,method:"DELETE",...l.apiClientParams}))),d=[];return f.forEach(D=>{if(D.status==="fulfilled")d.push(D.value);else throw D.reason}),s==="many"?d:d[0]},onSuccess:(...l)=>{if(i){let T=l[1],h=T.extraResources?[...a,...T.extraResources]:a,f=[P.getList(T.resource),P.getInfiniteList(T.resource)];h.forEach(d=>{f.push(P.getList(d)),f.push(P.getInfiniteList(d))}),q({queryKeys:f})}t?.onSuccess&&t.onSuccess(...l)},onError:(...l)=>{t?.onError&&t.onError(...l),x()}});return{mutation:K,delete:async({resourceParams:l,undoMessage:T,...h})=>{let f={path:e,params:l},d=s==="many"?h.ids:[h.id];if(r.optimistic){let D=h.extraResources?[...a,...h.extraResources]:a,b=o?P.getOneArray(f,d):[],M=o?[P.getList(f)]:[],F=o?[P.getInfiniteList(f)]:[];D.forEach(A=>{b.push(...P.getOneArray(A,d)),M.push(P.getList(A)),F.push(P.getInfiniteList(A))}),m.current=await N([...b,...M,...F]),se({ids:d,queryKeysOne:b,queryKeysList:M,queryKeysInfiniteList:F})}if(r.undoable&&!S){let D=d.length>1;O.once("end",b=>{b?x():g({...h,resource:f})}),y({message:T||`Element${D?"s":""} deleted`,type:D?"delete-many":"delete-one"})}else g({...h,resource:f})}}},Or=e=>ie({...e,type:"one"}),Sr=e=>ie({...e,type:"many"});import{useMutation as Le,useQueryClient as qe}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:o=!0,shouldInvalidateCache:i=!0,type:s="many"})=>{let{apiUrl:p,apiClient:n,apiEnsureTrailingSlash:u,toastUndo:y}=E(),c=qe(),m=Ae([]),x=()=>{m.current.forEach(([l,T])=>{c.setQueryData(l,T)})},{mutate:g,...K}=Le({...t,mutationKey:[s==="many"?"update-many":"update-one",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async l=>{let T=`${p}/${R(l.resource,!0)}`;if(t?.mutationFn)return await t?.mutationFn({apiClient:n,apiUrl:p,variables:l,url:T});let h=s==="many"?l.ids:[l.id],f=await Promise.allSettled(h.map(D=>n({url:`${T}${D}${u?"/":""}`,method:"PATCH",data:l.data,...l.apiClientParams}))),d=[];return f.forEach(D=>{if(D.status==="fulfilled")d.push(D.value);else throw D.reason}),s==="many"?d:d[0]},onSuccess:(...l)=>{if(i){let T=l[1],h=T.extraResources?[...a,...T.extraResources]:a,f=s==="many"?T.ids:[T.id],d=[...P.getOneArray(T.resource,f),P.getList(T.resource),P.getInfiniteList(T.resource)];h.forEach(D=>{d.push(...P.getOneArray(D,f)),d.push(P.getList(D)),d.push(P.getInfiniteList(D))}),q({queryKeys:d})}t?.onSuccess&&t.onSuccess(...l)},onError:(...l)=>{t?.onError&&t.onError(...l),x()}});return{mutation:K,update:async({resourceParams:l,undoMessage:T,...h})=>{let f={path:e,params:l},d=s==="many"?h.ids:[h.id];if(r.optimistic){let D=h.extraResources?[...a,...h.extraResources]:a,b=o?P.getOneArray(f,d):[],M=o?[P.getList(f)]:[],F=o?[P.getInfiniteList(f)]:[];D.forEach(W=>{b.push(...P.getOneArray(W,d)),M.push(P.getList(W)),F.push(P.getInfiniteList(W))}),m.current=await N([...b,...M,...F]);let A=h?.transformCacheData?h.transformCacheData(h.data):void 0;ne({data:A||h.data,ids:d,queryKeysOne:b,queryKeysList:M,queryKeysInfiniteList:F,overwriteOnTypeMismatch:h.cacheOverwriteOnTypeMismatch,overwriteOnTypeMismatchKeys:h.cacheOverwriteOnTypeMismatchKeys})}if(r.undoable&&!S){let D=d.length>1;O.once("end",b=>{b?x():g({...h,resource:f})}),y({message:T||`Element${D?"s":""} updated`,type:D?"update-many":"update-one"})}else g({...h,resource:f})}}},$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:o="start",shouldInvalidateCache:i=!0})=>{let{apiUrl:s,apiClient:p,apiEnsureTrailingSlash:n}=E(),{mutate:u,...y}=Ue({...t,mutationKey:["create",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async m=>{let x=`${s}/${R(m.resource,n)}`;return t?.mutationFn?await t?.mutationFn({apiClient:p,apiUrl:s,variables:m,url:x}):await p({url:x,method:"POST",data:m.data,...m.apiClientParams})},onSuccess:(...m)=>{let x=m[0],g=m[1],K=g.extraResources?[...r,...g.extraResources]:r;if(x){let Q=m[1],l=a?[P.getList(Q.resource)]:[],T=a?[P.getInfiniteList(Q.resource)]:[];K.forEach(f=>{l.push(P.getList(f)),T.push(P.getInfiniteList(f))});let h=Array.isArray(x)?x:[x];h.forEach(f=>{if(f){let{id:d}=f.data,D=a?[P.getOne(Q.resource,d)]:[];K.forEach(b=>{D.push(P.getOne(b,d))}),te({data:f,queryKeysOne:D.map(b=>[...b,{}])})}}),re({data:h.map(f=>f?.data||{}),cacheAddItemTo:o,queryKeysInfiniteList:T,queryKeysList:l}),i&&q({queryKeys:[...l,...T]})}t?.onSuccess&&t.onSuccess(...m)}});return{mutation:y,create:({resourceParams:m,...x})=>{u({...x,resource:{path:e,params:m}})}}};import{useQuery as Ie}from"@tanstack/react-query";var Zr=({queryOptions:e,resource:t,params:r={},apiClientParams:a})=>{let{apiUrl:o,apiClient:i,apiEnsureTrailingSlash:s}=E();return Ie({...e,queryKey:["query-data",t.path,t.params,r,...e?.queryKey?e.queryKey:[]],queryFn:async({queryKey:n})=>{let u={resource:t,params:r,queryKey:n},y=`${o}/${R(u.resource,s)}`;return e?.queryFn?await e?.queryFn({apiClient:i,apiUrl:o,variables:u,url:y}):await i({url:y,method:"GET",params:r,...a})}})};import{useMutation as we}from"@tanstack/react-query";var sa=({resourcePath:e,mutationOptions:t})=>{let{apiUrl:r,apiClient:a,apiEnsureTrailingSlash:o}=E(),{mutate:i,...s}=we({...t,mutationKey:["mutate-data",e,...t?.mutationKey?t.mutationKey:[]],mutationFn:async n=>{let u=`${r}/${R(n.resource,o)}`;return t?.mutationFn?await t?.mutationFn({apiClient:a,apiUrl:r,variables:n,url:u}):await a({url:u,data:n.data,...n.apiClientParams})}});return{mutation:s,mutate:async({resourceParams:n,...u})=>{i({...u,resource:{path:e,params:n}})}}};export{U as CustomError,xt as RQWrapper,et as ToastBar,te as addItemToQueryCache,re as addItemsToListQueryCache,se as deleteItemsFromQueryCache,j as fetcher,R as getUrlFromResource,P as helpersQueryKeys,Xt as invalidateMatchingQueries,q 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,Sr as useDeleteMany,Or as useDeleteOne,Lt as useGetInfiniteList,bt as useGetList,wt as useGetOne,E as useRQWrapperContext,Br as useUpdateMany,$r as useUpdateOne}; //# sourceMappingURL=index.mjs.map