use-sync-react
Version:
A package for keep updating the states with more features
1 lines • 11.3 kB
JavaScript
(()=>{"use strict";var e={d:(r,t)=>{for(var n in t)e.o(t,n)&&!e.o(r,n)&&Object.defineProperty(r,n,{enumerable:!0,get:t[n]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},r={};e.r(r),e.d(r,{clearCache:()=>k,syncIndividual:()=>U,useSync:()=>S});const t=require("react"),n=require("react-redux");var o,c,a=function(){return a=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var o in r=arguments[t])Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);return e},a.apply(this,arguments)},i=function(e,r,t,n){return new(t||(t=Promise))((function(o,c){function a(e){try{u(n.next(e))}catch(e){c(e)}}function i(e){try{u(n.throw(e))}catch(e){c(e)}}function u(e){var r;e.done?o(e.value):(r=e.value,r instanceof t?r:new t((function(e){e(r)}))).then(a,i)}u((n=n.apply(e,r||[])).next())}))},u=function(e,r){var t,n,o,c={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=i(0),a.throw=i(1),a.return=i(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(i){return function(u){return function(i){if(t)throw new TypeError("Generator is already executing.");for(;a&&(a=0,i[0]&&(c=0)),c;)try{if(t=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return c.label++,{value:i[1],done:!1};case 5:c.label++,n=i[1],i=[0];continue;case 7:i=c.ops.pop(),c.trys.pop();continue;default:if(!(o=c.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){c=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){c.label=i[1];break}if(6===i[0]&&c.label<o[1]){c.label=o[1],o=i;break}if(o&&c.label<o[2]){c.label=o[2],c.ops.push(i);break}o[2]&&c.ops.pop(),c.trys.pop();continue}i=r.call(e,c)}catch(e){i=[6,e],n=0}finally{t=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},s=function(e,r){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)r.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(t[n[o]]=e[n[o]])}return t},f=function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},l=function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,o,c=t.call(e),a=[];try{for(;(void 0===r||r-- >0)&&!(n=c.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(t=c.return)&&t.call(c)}finally{if(o)throw o.error}}return a},d=function(e,r,t){if(t||2===arguments.length)for(var n,o=0,c=r.length;o<c;o++)!n&&o in r||(n||(n=Array.prototype.slice.call(r,0,o)),n[o]=r[o]);return e.concat(n||Array.prototype.slice.call(r))},y=[],v=new Map;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(o||(o={}));var p,h=function(e){if(c&&c.throwError)throw new Error(e);console.error(e)},g={DEBUG:"color: #5bc0de",INFO:"color: #28a745",WARN:"color: #ffc107",ERROR:"color: #dc3545",DEFAULT:""},w=function(e,r,t){if(void 0===r&&(r="INFO"),(null==c?void 0:c.log)&&function(e){if(!(null==c?void 0:c.logLevel))return!0;var r=o[c.logLevel];return o[e]>=r}(r)){var n=(new Date).toISOString(),a="[".concat(n,"] %c").concat(r.toUpperCase(),"%c: ").concat(e);if(c.logger)return c.logger(r,e);t?console[r.toLowerCase()](a,g[r],g.DEFAULT,t):console[r.toLowerCase()](a,g[r],g.DEFAULT)}},E=new Map,b=new Map,m=new Map,O=5e3,k=function(e){e?E.delete(e):E.clear()},R=function(e,r){var t,n;if(!r||0===Object.keys(r).length)return e;var o=new URLSearchParams;try{for(var c=f(Object.entries(r)),a=c.next();!a.done;a=c.next()){var i=l(a.value,2),u=i[0],s=i[1];null!=s&&o.append(u,String(s))}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}var d=o.toString();return d?"".concat(e).concat(e.includes("?")?"&":"?").concat(d):e},S=function(e){var r=e.fetchOrder,o=e.fetchItems,g=e.throwError,S=void 0===g||g,D=e.cacheDuration,x=e.logLevel,P=void 0===x?"DEBUG":x,I=s(e,["fetchOrder","fetchItems","throwError","cacheDuration","logLevel"]);r=r.sort((function(e,r){return r.priority-e.priority}));var j=(0,t.useRef)(!1),A=(0,t.useRef)(a({fetchOrder:r,fetchItems:o,throwError:S,logLevel:P},I));O=D||O,c=A.current,v=A.current.fetchItems,y=A.current.fetchOrder;var L=l((0,t.useState)({isPending:!0,haveError:!1}),2),B=L[0],G=L[1],F=l((0,t.useState)(new Set),2),N=F[0],C=F[1];(0,t.useEffect)((function(){G((function(e){return a(a({},e),{isPending:N.size>0})}))}),[N]);var T=(0,t.useRef)([]),M=(0,n.useDispatch)();p=M;var q=(0,t.useCallback)((function(e){for(var r=[],t=1;t<arguments.length;t++)r[t-1]=arguments[t];return i(void 0,d([e],l(r),!1),void 0,(function(e,r){return void 0===r&&(r={}),u(this,(function(t){switch(t.label){case 0:return[4,U(e,r,null,M)];case 1:return t.sent(),[2]}}))}))}),[M]),W=(0,t.useCallback)((function(e,r){return i(void 0,void 0,void 0,(function(){var t,n,o,c,a;return u(this,(function(s){C((function(r){return new Set(d(d([],l(Array.from(r)),!1),[e.key],!1))}));try{return t="".concat(e.key,"-").concat(r),n=Date.now(),(o=E.get(t))&&n<o.expiresAt?(w("Using cached data for ".concat(e.key),"DEBUG"),[2,o.data]):(c=b.get(t))&&n-c.timestamp<5e3?(w("Reusing pending request for ".concat(e.key),"DEBUG"),[2,c.promise]):(a=i(void 0,void 0,void 0,(function(){var o,c,a,i,s;return u(this,(function(u){switch(u.label){case 0:return u.trys.push([0,,3,4]),w("Making fresh request for ".concat(e.key),"DEBUG"),o=null===(s=e.options)||void 0===s?void 0:s.params,c=o?R(r,o):r,[4,fetch(c,e.options||{})];case 1:if(!(a=u.sent()).ok)throw w("Request failed for ".concat(e.key),"ERROR",{status:a.status}),new Error("Failed to fetch ".concat(e.key));return[4,a.json()];case 2:return i=u.sent(),E.set(t,{data:i,timestamp:n,expiresAt:n+O}),w("Cached new data for ".concat(e.key),"DEBUG",{expiresAt:new Date(n+O)}),[2,i];case 3:return b.delete(t),[7];case 4:return[2]}}))})),b.set(t,{timestamp:n,promise:a}),[2,a])}finally{}return[2]}))}))}),[]),z=(0,t.useCallback)((function(){return i(void 0,void 0,void 0,(function(){var e,r,t,n,o,c,s,y,v,p,g,E,b,O,k,R,S;return u(this,(function(D){switch(D.label){case 0:if(!j.current)return[2];D.label=1;case 1:return D.trys.push([1,3,4,5]),G({isPending:!0,haveError:!1}),w("Starting sync process","INFO"),e=[],r=[],t=[],n=A.current.fetchOrder,o=A.current.fetchItems,n.forEach((function(n){n.refetchOnline&&e.push(n.key),n.refetchOnFocus&&r.push(n.key),n.triggerEvents&&t.push({events:"string"==typeof n.triggerEvents?[n.triggerEvents]:n.triggerEvents,key:n.key})})),c=function(){w("Online event triggered","DEBUG"),e.forEach((function(e){return q(e)}))},s=function(){w("Focus event triggered","DEBUG"),r.forEach((function(e){return q(e)}))},window.addEventListener("online",c),window.addEventListener("focus",s),y=new Map,t.forEach((function(e){var r=e.key;e.events.forEach((function(e){var t=function(){w('Window event "'.concat(e,'" triggered for ').concat(r),"DEBUG"),q(r)};y.set("".concat(r,"-").concat(e),t),"undefined"!=typeof window&&window.addEventListener(e,t)}))})),v=n.map((function(e){return i(void 0,void 0,void 0,(function(){var r,t,n;return u(this,(function(c){switch(c.label){case 0:if("object"==typeof e.includedPaths&&Array.isArray(e.includedPaths)&&(r=window.location.pathname,!e.includedPaths.includes(r)))return w("Skipping ".concat(e.key," - not in included paths"),"WARN"),[2];if("boolean"==typeof e.initialSync&&!e.initialSync)return[2];if("boolean"==typeof e.backgroundSync&&e.backgroundSync)return C((function(r){var t=new Set(r);return t.delete(e.key),t})),[2,m.set(e.key,(function(){return q(e.key)}))];if(T.current.includes(e.key))return w("Skipping ".concat(e.key," - already pending"),"WARN"),[2];if(!(t=o.get(e.key)))return w("URL not found for ".concat(e.key),"ERROR"),[2,h("url not found for ".concat(e.key))];T.current=d(d([],l(T.current),!1),[e.key],!1),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,W(e,t)];case 2:return n=c.sent(),C((function(r){var t=new Set(r);return t.delete(e.key),t})),j.current&&M(e.action(n)),[3,4];case 3:return j.current&&(T.current=T.current.filter((function(r){return r!==e.key}))),[7];case 4:return[2]}}))}))})).filter(Boolean),[4,Promise.all(v)];case 2:if(D.sent(),j.current){G({isPending:!1,haveError:!1}),p=Array.from(m.entries());try{for(g=f(p),E=g.next();!E.done;E=g.next())b=l(E.value,2),O=b[0],(0,b[1])(),m.delete(O)}catch(e){R={error:e}}finally{try{E&&!E.done&&(S=g.return)&&S.call(g)}finally{if(R)throw R.error}}}return[2,function(){w("Cleaning up event listeners","DEBUG"),window.removeEventListener("online",c),window.removeEventListener("focus",s),t.forEach((function(e){var r=e.key;e.events.forEach((function(e){var t=y.get("".concat(r,"-").concat(e));t&&"undefined"!=typeof window&&window.removeEventListener(e,t)}))})),y.clear()}];case 3:return k=D.sent(),G((function(e){return a(a({},e),{haveError:!0})})),w("Sync process failed","ERROR",{error:k}),A.current.onError&&A.current.onError(k),[3,5];case 4:return[7];case 5:return[2]}}))}))}),[M,W,q]);return(0,t.useEffect)((function(){j.current=!0;var e=z();return function(){j.current=!1,e.then((function(e){return e&&e()}))}}),[z]),{isPending:B.isPending||N.size>0,haveError:B.haveError,clearCache:k,refresh:z,loadingItems:Array.from(N)}},D=[],U=function(e){for(var r=[],t=1;t<arguments.length;t++)r[t-1]=arguments[t];return i(void 0,d([e],l(r),!1),void 0,(function(e,r,t,n){var o,c,i,s,f,l,d,g,E;return void 0===r&&(r={}),void 0===n&&(n=p),u(this,(function(u){switch(u.label){case 0:if(o="individual-".concat(e),b.get(o))return w("Request already pending for ".concat(e),"DEBUG"),[2];if(D.includes(e))return w("Skipping duplicate fetch for ".concat(e),"DEBUG"),[2];w("Starting individual sync for ".concat(e),"INFO"),D.push(e),u.label=1;case 1:return u.trys.push([1,7,8,9]),c=y.find((function(r){return r.key===e})),(i=v.get(e))&&c?(s=a(a({},c.options),r),f=s.path?"".concat(i).concat(s.path):i,l=s.params?R(f,s.params):f,[4,fetch(l,s)]):(w("Configuration not found for ".concat(e),"ERROR"),[2,h("no url found for item ".concat(e))]);case 2:if(!(d=u.sent()).ok)throw w("Sync failed for ".concat(e),"ERROR",{status:d.status,statusText:d.statusText}),new Error("Failed to fetch ".concat(e," ").concat(d.statusText));return g=null,c.transformResponse?[3,4]:[4,d.json()];case 3:return g=u.sent(),[3,6];case 4:return[4,c.transformResponse(d)];case 5:g=u.sent(),u.label=6;case 6:return w("Individual sync successful for ".concat(e),"INFO",{dataSize:JSON.stringify(g).length}),n("function"==typeof t?t(g):c.action(g)),[2,g];case 7:return E=u.sent(),w("Sync error : ".concat(E),"ERROR"),[3,9];case 8:return D=D.filter((function(r){return r!==e})),w("Completed individual sync for ".concat(e),"DEBUG"),[7];case 9:return[2]}}))}))};module.exports=r})();