UNPKG

react-native-storage

Version:

A local storage wrapper for both react-native(AsyncStorage) and browser(localStorage).

3 lines (2 loc) 11.1 kB
"use strict";function asyncGeneratorStep(e,t,r,n,i,a,o){try{var s=e[a](o),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var a=e.apply(t,r);function o(e){asyncGeneratorStep(a,n,i,o,s,"next",e)}function s(e){asyncGeneratorStep(a,n,i,o,s,"throw",e)}o(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){_defineProperty(e,t,r[t])})}return e}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function _construct(e,t,r){return(_construct=isNativeReflectConstruct()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}).apply(null,arguments)}function _isNativeFunction(e){return-1!==Function.toString.call(e).indexOf("[native code]")}function _wrapNativeSuper(e){var t="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function(e){if(null===e||!_isNativeFunction(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return _construct(e,arguments,_getPrototypeOf(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(r,e)})(e)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _possibleConstructorReturn(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?_assertThisInitialized(e):t}Object.defineProperty(exports,"__esModule",{value:!0});var NotFoundError=function(e){function t(e){var r;return _classCallCheck(this,t),(r=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,"Not Found! Params: ".concat(e)))).name="NotFoundError",r.stack=(new Error).stack,r}return _inherits(t,_wrapNativeSuper(Error)),t}(),ExpiredError=function(e){function t(e){var r;return _classCallCheck(this,t),(r=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,"Expired! Params: ".concat(e)))).name="ExpiredError",r.stack=(new Error).stack,r}return _inherits(t,_wrapNativeSuper(Error)),t}(),Storage=function(){function e(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(_classCallCheck(this,e),this._SIZE=r.size||1e3,this.sync=r.sync||{},this.defaultExpires=void 0!==r.defaultExpires?r.defaultExpires:864e5,this.enableCache=!1!==r.enableCache,this._s=r.storageBackend||null,this._innerVersion=11,this.cache={},this._s&&this._s.setItem)try{var n=this._s.setItem("__react_native_storage_test","test");this.isPromise=!(!n||!n.then)}catch(e){throw console.warn(e),delete this._s,e}else console.warn("Data would be lost after reload cause there is no storageBackend specified!\n \nEither use localStorage(for web) or AsyncStorage(for React Native) as a storageBackend.");this._mapPromise=this.getItem("map").then(function(e){t._m=t._checkMap(e&&JSON.parse(e)||{})})}var t;return _createClass(e,[{key:"getItem",value:function(e){return this._s?this.isPromise?this._s.getItem(e):Promise.resolve(this._s.getItem(e)):Promise.resolve()}},{key:"setItem",value:function(e,t){return this._s?this.isPromise?this._s.setItem(e,t):Promise.resolve(this._s.setItem(e,t)):Promise.resolve()}},{key:"removeItem",value:function(e){return this._s?this.isPromise?this._s.removeItem(e):Promise.resolve(this._s.removeItem(e)):Promise.resolve()}},{key:"_initMap",value:function(){return{innerVersion:this._innerVersion,index:0,__keys__:{}}}},{key:"_checkMap",value:function(e){return e&&e.innerVersion&&e.innerVersion===this._innerVersion?e:this._initMap()}},{key:"_getId",value:function(e,t){return e+"_"+t}},{key:"_saveToMap",value:function(e){var t=e.key,r=e.id,n=e.data,i=this._getId(t,r),a=this._m;if(void 0!==a[i])return this.enableCache&&(this.cache[i]=JSON.parse(n)),this.setItem("map_"+a[i],n);if(void 0!==a[a.index]){var o=a[a.index],s=o.split("_");delete a[o],this._removeIdInKey(s[0],s[1]),this.enableCache&&delete this.cache[o]}if(a[i]=a.index,a[a.index]=i,a.__keys__[t]=a.__keys__[t]||[],a.__keys__[t].push(r),this.enableCache){var c=JSON.parse(n);this.cache[i]=c}var u=a.index;++a.index===this._SIZE&&(a.index=0),this.setItem("map_"+u,n),this.setItem("map",JSON.stringify(a))}},{key:"save",value:function(e){var t=this,r=e.key,n=e.id,i=e.data,a=e.rawData,o=e.expires,s=void 0===o?this.defaultExpires:o;-1!==r.toString().indexOf("_")&&console.error('Please do not use "_" in key!');var c={rawData:i};if(void 0===i){if(void 0===a)return void console.error('"data" is required in save()!');console.warn('"rawData" is deprecated, please use "data" instead!'),c.rawData=a}var u=Date.now();if(null!==s&&(c.expires=u+s),c=JSON.stringify(c),void 0===n){if(this.enableCache){var h=JSON.parse(c);this.cache[r]=h}return this.setItem(r,c)}return-1!==n.toString().indexOf("_")&&console.error('Please do not use "_" in id!'),this._mapPromise.then(function(){return t._saveToMap({key:r,id:n,data:c})})}},{key:"getBatchData",value:function(e){var t=this;return Promise.all(e.map(function(e){return t.load(e)}))}},{key:"getBatchDataWithIds",value:(t=_asyncToGenerator(regeneratorRuntime.mark(function e(t){var r,n,i,a,o,s,c,u,h=this;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.key,n=t.ids,i=t.syncInBackground,a=t.syncParams,o=n.map(function(e){return h.load({key:r,id:e,syncInBackground:i,autoSync:!1,batched:!0})}),e.next=4,Promise.all(o);case 4:if(s=e.sent,c=[],s.forEach(function(e){void 0!==e.syncId&&c.push(e.syncId)}),!c.length){e.next=14;break}return e.next=10,this.sync[r]({id:c,syncParams:a});case 10:return u=e.sent,e.abrupt("return",s.map(function(e){return e.syncId?u.shift():e}));case 14:return e.abrupt("return",s);case 15:case"end":return e.stop()}},e,this)})),function(e){return t.apply(this,arguments)})},{key:"_lookupGlobalItem",value:function(e){var t=this,r=e.key;return this.enableCache&&void 0!==this.cache[r]?this._loadGlobalItem(_objectSpread({ret:this.cache[r]},e)):this.getItem(r).then(function(r){return t._loadGlobalItem(_objectSpread({ret:r},e))})}},{key:"_loadGlobalItem",value:function(e){var t=e.key,r=e.ret,n=e.autoSync,i=e.syncInBackground,a=e.syncParams;if(null==r){if(n&&this.sync[t])return this.sync[t]({syncParams:a});throw new NotFoundError(JSON.stringify(e))}"string"==typeof r&&(r=JSON.parse(r),this.enableCache&&(this.cache[t]=r));var o=Date.now();if(r.expires<o){if(n&&this.sync[t]){if(i){try{this.sync[t]({syncParams:a,syncInBackground:i})}catch(e){}return r.rawData}return this.sync[t]({syncParams:a,syncInBackground:i})}throw new ExpiredError(JSON.stringify(e))}return r.rawData}},{key:"_noItemFound",value:function(e){var t=e.key,r=e.id,n=e.autoSync,i=e.syncParams;if(this.sync[t])return n?this.sync[t]({id:r,syncParams:i}):{syncId:r};throw new NotFoundError(JSON.stringify(e))}},{key:"_loadMapItem",value:function(e){var t=e.ret,r=e.key,n=e.id,i=e.autoSync,a=e.batched,o=e.syncInBackground,s=e.syncParams;if(null==t)return this._noItemFound(e);if("string"==typeof t){t=JSON.parse(t);var c=e.key,u=e.id,h=this._getId(c,u);this.enableCache&&(this.cache[h]=t)}var l=Date.now();if(t.expires<l){if(i&&this.sync[r]){if(o){try{this.sync[r]({id:n,syncParams:s,syncInBackground:o})}catch(e){}return t.rawData}return this.sync[r]({id:n,syncParams:s,syncInBackground:o})}if(a)return{syncId:n};throw new ExpiredError(JSON.stringify(e))}return t.rawData}},{key:"_lookUpInMap",value:function(e){var t,r=this,n=this._m,i=e.key,a=e.id,o=this._getId(i,a);return this.enableCache&&this.cache[o]?(t=this.cache[o],this._loadMapItem(_objectSpread({ret:t},e))):void 0!==n[o]?this.getItem("map_"+n[o]).then(function(t){return r._loadMapItem(_objectSpread({ret:t},e))}):this._noItemFound(_objectSpread({ret:t},e))}},{key:"remove",value:function(e){var t=this;return this._mapPromise.then(function(){var r=t._m,n=e.key,i=e.id;if(void 0===i)return t.enableCache&&t.cache[n]&&delete t.cache[n],t.removeItem(n);var a=t._getId(n,i);if(void 0!==r[a]){t.enableCache&&t.cache[a]&&delete t.cache[a],t._removeIdInKey(n,i);var o=r[a];return delete r[a],t.setItem("map",JSON.stringify(r)),t.removeItem("map_"+o)}})}},{key:"_removeIdInKey",value:function(e,t){var r=(this._m.__keys__[e]||[]).indexOf(t);-1!==r&&this._m.__keys__[e].splice(r,1)}},{key:"load",value:function(e){var t=this,r=e.key,n=e.id,i=e.autoSync,a=void 0===i||i,o=e.syncInBackground,s=void 0===o||o,c=e.syncParams,u=e.batched;return this._mapPromise.then(function(){return void 0===n?t._lookupGlobalItem({key:r,autoSync:a,syncInBackground:s,syncParams:c}):t._lookUpInMap({key:r,id:n,autoSync:a,syncInBackground:s,batched:u,syncParams:c})})}},{key:"clearAll",value:function(){this._s.clear&&this._s.clear(),this._m=this._initMap()}},{key:"clearMap",value:function(){var e=this;return this.removeItem("map").then(function(){e.cache={},e._m=e._initMap()})}},{key:"clearMapForKey",value:function(e){var t=this;return this._mapPromise.then(function(){var r=(t._m.__keys__[e]||[]).map(function(r){return t.remove({key:e,id:r})});return Promise.all(r)})}},{key:"getIdsForKey",value:function(e){var t=this;return this._mapPromise.then(function(){return t._m.__keys__[e]||[]})}},{key:"getAllDataForKey",value:function(e,t){var r=this;return t=Object.assign({syncInBackground:!0},t),this.getIdsForKey(e).then(function(n){var i=n.map(function(r){return{key:e,id:r,syncInBackground:t.syncInBackground}});return r.getBatchData(i)})}}]),e}();exports.default=Storage; //# sourceMappingURL=storage.cjs.js.map