UNPKG

@ngx-pwa/local-storage

Version:

Efficient local storage module for Angular: simple API based on native localStorage API, but internally stored via the asynchronous IndexedDB API for performance, and wrapped in RxJS observables to be homogeneous with other Angular modules.

16 lines (14 loc) 17.9 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("@angular/common"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define("@ngx-pwa/local-storage",["exports","@angular/core","@angular/common","rxjs","rxjs/operators"],t):t(((e=e||self)["ngx-pwa"]=e["ngx-pwa"]||{},e["ngx-pwa"]["local-storage"]={}),e.ng.core,e.ng.common,e.rxjs,e.rxjs.operators)}(this,(function(e,t,r,n,o){"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function a(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}Object.create;function s(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.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(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a}function c(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(u(arguments[t]));return e}Object.create;var p=function(){function e(){}return e.prototype.validate=function(e,t){switch(t.type){case"string":return this.validateString(e,t);case"number":case"integer":return this.validateNumber(e,t);case"boolean":return this.validateBoolean(e,t);case"array":return this.validateArray(e,t);case"object":return this.validateObject(e,t)}},e.prototype.validateString=function(e,t){if("string"!=typeof e)return!1;if(!this.validateConst(e,t))return!1;if(!this.validateEnum(e,t))return!1;if(void 0!==t.maxLength&&e.length>t.maxLength)return!1;if(void 0!==t.minLength&&e.length<t.minLength)return!1;if(t.pattern){var r=null;try{r=new RegExp(t.pattern)}catch(e){}if(r&&!r.test(e))return!1}return!0},e.prototype.validateNumber=function(e,t){return"number"==typeof e&&(!("integer"===t.type&&!Number.isInteger(e))&&(!!this.validateConst(e,t)&&(!!this.validateEnum(e,t)&&(!(t.multipleOf&&!Number.isInteger(e/t.multipleOf))&&(!(void 0!==t.maximum&&e>t.maximum)&&(!(void 0!==t.exclusiveMaximum&&e>=t.exclusiveMaximum)&&(!(void 0!==t.minimum&&e<t.minimum)&&!(void 0!==t.exclusiveMinimum&&e<=t.exclusiveMinimum))))))))},e.prototype.validateBoolean=function(e,t){return"boolean"==typeof e&&!!this.validateConst(e,t)},e.prototype.validateArray=function(e,t){var r,n;if(!Array.isArray(e))return!1;if(void 0!==t.maxItems&&e.length>t.maxItems)return!1;if(void 0!==t.minItems&&e.length<t.minItems)return!1;if(t.uniqueItems){var o=new Set(e);if(e.length!==o.size)return!1}if(Array.isArray(t.items))return this.validateTuple(e,t.items);try{for(var i=s(e),a=i.next();!a.done;a=i.next()){var u=a.value;if(!this.validate(u,t.items))return!1}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return!0},e.prototype.validateTuple=function(e,t){if(e.length!==t.length)return!1;for(var r=0;r<t.length;r+=1)if(!this.validate(e[r],t[r]))return!1;return!0},e.prototype.validateObject=function(e,t){var r,n;if("object"!=typeof e||null===e)return!1;if(Object.keys(t.properties).length<Object.keys(e).length)return!1;if(t.required)try{for(var o=s(t.required),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.hasOwnProperty(a))return!1}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}for(var u in t.properties)if(t.properties.hasOwnProperty(u)&&e.hasOwnProperty(u)&&!this.validate(e[u],t.properties[u]))return!1;return!0},e.prototype.validateConst=function(e,t){return!t.const||e===t.const},e.prototype.validateEnum=function(e,t){return!t.enum||t.enum.includes(e)},e}();p.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new p},token:p,providedIn:"root"}),p.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}];var f=new t.InjectionToken("localStoragePrefix",{providedIn:"root",factory:function(){return""}}),l=new t.InjectionToken("localStorageIDBDBName",{providedIn:"root",factory:function(){return"ngStorage"}}),d=new t.InjectionToken("localStorageIDBDBVersion",{providedIn:"root",factory:function(){return 1}}),y=new t.InjectionToken("localStorageIDBStoreName",{providedIn:"root",factory:function(){return"localStorage"}}),v=new t.InjectionToken("localStorageIDBWrap",{providedIn:"root",factory:function(){return!0}}),h=function(e){function t(){var t=e.apply(this,c(arguments))||this;return t.message="indexedDB is not working",t}return a(t,e),t}(Error),g="The storage is currently localStorage,\nwhere data must be serialized, and the provided data can't be serialized.",m=function(e){function t(){var t=e.apply(this,c(arguments))||this;return t.message=g,t}return a(t,e),t}(Error),b=function(){function e(e,t,r,o){void 0===e&&(e="ngStorage"),void 0===t&&(t="localStorage"),void 0===r&&(r=1),void 0===o&&(o=!0),this.database=new n.ReplaySubject(1),this.wrapIndex="value",this.dbName=e,this.storeName=t,this.dbVersion=r,this.noWrap=o,this.connect()}return Object.defineProperty(e.prototype,"backingStore",{get:function(){return{database:this.dbName,store:this.storeName,version:this.dbVersion}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.transaction("readonly").pipe(o.mergeMap((function(e){var t=e.store,r=e.events,n=t.count();return r.pipe(o.map((function(){return n.result})))})),o.first())},enumerable:!1,configurable:!0}),e.prototype.get=function(e){var t=this;return this.transaction("readonly").pipe(o.mergeMap((function(r){var n=r.store,i=r.events,a=n.get(e);return i.pipe(o.map((function(){if(void 0!==a.result&&null!==a.result)return!t.noWrap&&"object"==typeof a.result&&t.wrapIndex in a.result&&void 0!==a.result[t.wrapIndex]&&null!==a.result[t.wrapIndex]?a.result[t.wrapIndex]:a.result})))})),o.first())},e.prototype.set=function(e,t){var r=this;return void 0===t?this.delete(e):this.transaction("readwrite").pipe(o.mergeMap((function(n){var i,a=n.store,s=n.events,u=r.noWrap?t:((i={})[r.wrapIndex]=t,i);return a.put(u,e),s.pipe(o.mapTo(void 0))})),o.first())},e.prototype.delete=function(e){return this.transaction("readwrite").pipe(o.mergeMap((function(t){var r=t.store,n=t.events;return r.delete(e),n.pipe(o.mapTo(void 0))})),o.first())},e.prototype.clear=function(){return this.transaction("readwrite").pipe(o.mergeMap((function(e){var t=e.store,r=e.events;return t.clear(),r.pipe(o.mapTo(void 0))})),o.first())},e.prototype.keys=function(){var e=this;return this.transaction("readonly").pipe(o.first(),o.mergeMap((function(t){var r=t.store,i="openKeyCursor"in r?r.openKeyCursor():r.openCursor(),a=n.fromEvent(i,"success").pipe(o.takeWhile((function(){return null!==i.result})),o.map((function(){return i.result.key.toString()})),o.tap((function(){i.result.continue()}))),s=e.listenError(i);return n.race([a,s])})))},e.prototype.has=function(e){return this.transaction("readonly").pipe(o.mergeMap((function(t){var r=t.store,n=t.events,i="getKey"in r?r.getKey(e):r.get(e);return n.pipe(o.map((function(){return void 0!==i.result})))})),o.first())},e.prototype.connect=function(){var e,t=this;try{e=indexedDB.open(this.dbName,this.dbVersion)}catch(e){return void this.database.error(new h)}this.createStore(e);var r=n.fromEvent(e,"success"),i=this.listenError(e);n.race([r,i]).pipe(o.first()).subscribe({next:function(){t.database.next(e.result)},error:function(){t.database.error(new h)}})},e.prototype.createStore=function(e){var t=this;n.fromEvent(e,"upgradeneeded").pipe(o.first()).subscribe({next:function(){e.result.objectStoreNames.contains(t.storeName)||e.result.createObjectStore(t.storeName)}})},e.prototype.transaction=function(e){var t=this;return this.database.pipe(o.mergeMap((function(r){var o;try{o=r.transaction([t.storeName],e)}catch(e){return n.throwError(e)}var i=o.objectStore(t.storeName),a=t.listenTransactionEvents(o);return n.of({store:i,events:a})})))},e.prototype.listenError=function(e){return n.fromEvent(e,"error").pipe(o.mergeMap((function(e){return n.throwError(e.target.error)})))},e.prototype.listenTransactionEvents=function(e){var t=n.fromEvent(e,"complete"),r=this.listenError(e);return n.race([t,r])},e}();b.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new b(t.ɵɵinject(l),t.ɵɵinject(y),t.ɵɵinject(d),t.ɵɵinject(v))},token:b,providedIn:"root"}),b.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],b.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[l]}]},{type:void 0,decorators:[{type:t.Inject,args:[y]}]},{type:void 0,decorators:[{type:t.Inject,args:[d]}]},{type:void 0,decorators:[{type:t.Inject,args:[v]}]}]};var I=function(){function e(e){void 0===e&&(e=""),this.prefix=e||""}return Object.defineProperty(e.prototype,"size",{get:function(){return n.of(localStorage.length)},enumerable:!1,configurable:!0}),e.prototype.get=function(e){var t,r=localStorage.getItem(this.prefixKey(e));if(null!=r)try{t=JSON.parse(r)}catch(e){return n.throwError(e)}return n.of(t)},e.prototype.set=function(e,t){var r=null,o=Object.getPrototypeOf(t);if("object"==typeof t&&null!==t&&!Array.isArray(t)&&o!==Object.prototype&&null!==o)return n.throwError(new m);try{r=JSON.stringify(t)}catch(e){return n.throwError(e)}try{localStorage.setItem(this.prefixKey(e),r)}catch(e){return n.throwError(e)}return n.of(void 0)},e.prototype.delete=function(e){return localStorage.removeItem(this.prefixKey(e)),n.of(void 0)},e.prototype.clear=function(){return localStorage.clear(),n.of(void 0)},e.prototype.keys=function(){var e=this;return new n.Observable((function(t){for(var r=0;r<localStorage.length;r+=1)t.next(e.getUnprefixedKey(r));t.complete()})).pipe(o.observeOn(n.asyncScheduler))},e.prototype.has=function(e){for(var t=0;t<localStorage.length;t+=1)if(e===this.getUnprefixedKey(t))return n.of(!0);return n.of(!1)},e.prototype.getUnprefixedKey=function(e){var t=localStorage.key(e);return null!==t?this.prefix?t.substr(this.prefix.length):t:null},e.prototype.prefixKey=function(e){return""+this.prefix+e},e}();I.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new I(t.ɵɵinject(f))},token:I,providedIn:"root"}),I.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],I.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[f]}]}]};var j=function(){function e(){this.memoryStorage=new Map}return Object.defineProperty(e.prototype,"size",{get:function(){return n.of(this.memoryStorage.size)},enumerable:!1,configurable:!0}),e.prototype.get=function(e){var t=this.memoryStorage.get(e);return n.of(t)},e.prototype.set=function(e,t){return this.memoryStorage.set(e,t),n.of(void 0)},e.prototype.delete=function(e){return this.memoryStorage.delete(e),n.of(void 0)},e.prototype.clear=function(){return this.memoryStorage.clear(),n.of(void 0)},e.prototype.keys=function(){return n.from(this.memoryStorage.keys())},e.prototype.has=function(e){return n.of(this.memoryStorage.has(e))},e}();function x(e,t,n,o,i,a){try{if(r.isPlatformBrowser(e)&&void 0!==indexedDB&&null!==indexedDB&&"open"in indexedDB)return new b(n,o,i,a);if(r.isPlatformBrowser(e)&&void 0!==localStorage&&null!==localStorage&&"getItem"in localStorage)return new I(t)}catch(e){}return new j}j.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new j},token:j,providedIn:"root"}),j.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}];var w=function(){};w.ɵprov=t.ɵɵdefineInjectable({factory:function(){return x(t.ɵɵinject(t.PLATFORM_ID),t.ɵɵinject(f),t.ɵɵinject(l),t.ɵɵinject(y),t.ɵɵinject(d),t.ɵɵinject(v))},token:w,providedIn:"root"}),w.decorators=[{type:t.Injectable,args:[{providedIn:"root",useFactory:x,deps:[t.PLATFORM_ID,f,l,y,d,v]}]}];var S="Data stored is not valid against the provided JSON schema.\nCheck your JSON schema, otherwise it means data has been corrupted.",B=function(e){function t(){var t=e.apply(this,c(arguments))||this;return t.message=S,t}return a(t,e),t}(Error),O=function(){function e(e,t,r){void 0===t&&(t=new p),void 0===r&&(r=""),this.database=e,this.jsonValidator=t,this.LSPrefix=r,this.notifiers=new Map}return Object.defineProperty(e.prototype,"size",{get:function(){var e=this;return this.database.size.pipe(this.catchIDBBroken((function(){return e.database.size})))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"backingEngine",{get:function(){return this.database instanceof b?"indexedDB":this.database instanceof I?"localStorage":this.database instanceof j?"memory":"unknown"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"backingStore",{get:function(){return this.database instanceof b?this.database.backingStore:{database:"",store:"",version:0}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fallbackBackingStore",{get:function(){return this.database instanceof I?{prefix:this.database.prefix}:{prefix:""}},enumerable:!1,configurable:!0}),e.prototype.get=function(e,t){var r=this;return this.database.get(e).pipe(this.catchIDBBroken((function(){return r.database.get(e)})),o.mergeMap((function(e){return null==e?n.of(void 0):t?r.jsonValidator.validate(e,t)?n.of(e):n.throwError(new B):n.of(e)})))},e.prototype.set=function(e,t,r){var i=this;return null==t?this.delete(e):r&&!this.jsonValidator.validate(t,r)?n.throwError(new B):this.database.set(e,t).pipe(this.catchIDBBroken((function(){return i.database.set(e,t)})),o.tap((function(){i.notify(e,t)})))},e.prototype.delete=function(e){var t=this;return this.database.delete(e).pipe(this.catchIDBBroken((function(){return t.database.delete(e)})),o.tap((function(){t.notify(e,void 0)})))},e.prototype.clear=function(){var e=this;return this.database.clear().pipe(this.catchIDBBroken((function(){return e.database.clear()})),o.tap((function(){var t,r;try{for(var n=s(e.notifiers.keys()),o=n.next();!o.done;o=n.next()){var i=o.value;e.notify(i,void 0)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})))},e.prototype.keys=function(){var e=this;return this.database.keys().pipe(this.catchIDBBroken((function(){return e.database.keys()})))},e.prototype.has=function(e){var t=this;return this.database.has(e).pipe(this.catchIDBBroken((function(){return t.database.has(e)})))},e.prototype.watch=function(e,t){var r=this.notifiers.get(e);return r||(r=new n.ReplaySubject(1),this.notifiers.set(e,r),this.get(e,t).subscribe({next:function(e){return r.next(e)},error:function(e){return r.error(e)}})),r.asObservable()},e.prototype.notify=function(e,t){var r=this.notifiers.get(e);r&&r.next(t)},e.prototype.catchIDBBroken=function(e){var t=this;return o.catchError((function(r){if(null!=r&&"indexedDB is not working"===r.message){try{"getItem"in localStorage?t.database=new I(t.LSPrefix):t.database=new j}catch(e){t.database=new j}return e()}return n.throwError(r)}))},e}();O.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new O(t.ɵɵinject(w),t.ɵɵinject(p),t.ɵɵinject(f))},token:O,providedIn:"root"}),O.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],O.ctorParameters=function(){return[{type:w},{type:p},{type:void 0,decorators:[{type:t.Inject,args:[f]}]}]};var k=function(){function e(e){this.storageMap=e}return Object.defineProperty(e.prototype,"length",{get:function(){return this.storageMap.size},enumerable:!1,configurable:!0}),e.prototype.getItem=function(e,t){if(t){var r="schema"in t?t.schema:t;return this.storageMap.get(e,r).pipe(o.map((function(e){return void 0!==e?e:null})))}return this.storageMap.get(e).pipe(o.map((function(e){return void 0!==e?e:null})))},e.prototype.setItem=function(e,t,r){return this.storageMap.set(e,t,r).pipe(o.mapTo(!0))},e.prototype.removeItem=function(e){return this.storageMap.delete(e).pipe(o.mapTo(!0))},e.prototype.clear=function(){return this.storageMap.clear().pipe(o.mapTo(!0))},e}();k.ɵprov=t.ɵɵdefineInjectable({factory:function(){return new k(t.ɵɵinject(O))},token:k,providedIn:"root"}),k.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],k.ctorParameters=function(){return[{type:O}]};var D=function(){function e(){}return e.forRoot=function(t){return{ngModule:e,providers:[t.LSPrefix?{provide:f,useValue:t.LSPrefix}:[],t.IDBDBName?{provide:l,useValue:t.IDBDBName}:[],t.IDBStoreName?{provide:y,useValue:t.IDBStoreName}:[],t.IDBDBVersion?{provide:d,useValue:t.IDBDBVersion}:[],!1===t.IDBNoWrap?{provide:v,useValue:t.IDBNoWrap}:[]]}},e}();D.decorators=[{type:t.NgModule}],e.JSONValidator=p,e.LocalDatabase=w,e.LocalStorage=k,e.SERIALIZATION_ERROR=g,e.SerializationError=m,e.StorageMap=O,e.StorageModule=D,e.VALIDATION_ERROR=S,e.ValidationError=B,e.ɵa=x,e.ɵb=f,e.ɵc=l,e.ɵd=d,e.ɵe=y,e.ɵf=v,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=ngx-pwa-local-storage.umd.min.js.map