UNPKG

localstoredb

Version:

本地储存工具包,可设置存储时间,支持web和小程序

2 lines (1 loc) 11.2 kB
(function(l,o){typeof exports=="object"&&typeof module!="undefined"?module.exports=o():typeof define=="function"&&define.amd?define(o):(l=typeof globalThis!="undefined"?globalThis:l||self,l.LocalStore=o())})(this,function(){"use strict";var J=Object.defineProperty;var U=(l,o,p)=>o in l?J(l,o,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[o]=p;var c=(l,o,p)=>(U(l,typeof o!="symbol"?o+"":o,p),p);const l=Object.prototype.toString,o="2658236dccf04bd49c2aec9136fcf88c";function p(s,t){return new Blob([new Uint8Array(s.split(",")).buffer],{type:t})}function L(s){const t=URL.createObjectURL(s),e=new XMLHttpRequest;e.open("GET",t,!1),e.send(),URL.revokeObjectURL(t);const r=new Uint8Array(e.response.length);for(let i=0;i<e.response.length;++i)r[i]=e.response.charCodeAt(i);return r.toString()}const g=s=>{let t=s;if(typeof s=="string")try{t=s=JSON.parse(s)}catch(e){throw Error(e)}if(typeof s=="string"&&s.indexOf(o)>0){const[e,r,i]=s.split(o);e==="ArrayBuffer"?t=new Uint8Array(r.split(",").map(n=>parseInt(n))).buffer:e==="Blob"?t=p(i,r):t=new window[e](r.split(","))}else if(Array.isArray(s))t=[],s.forEach((e,r)=>{t[r]=g(e)});else if(typeof s=="object"){if(s===null)return null;t={};for(const e in s)t[e]=g(s[e])}return t},y=s=>{if(typeof s!="object")return JSON.stringify(s);if(s===null)return"null";if(Array.isArray(s))return JSON.stringify(s.map(e=>y(e)));const t=l.call(s).slice(8,-1);if(t==="Object"){let e={};for(let r in s)e[r]=y(s[r]);return JSON.stringify(e)}else t==="ArrayBuffer"?s=new Uint8Array(s):t==="Blob"&&(s=s.type+o+L(s));return t+o+s.toString()},x=(s,t)=>{const e=Date.now();return Object.keys(s).forEach(r=>{if(typeof s[r]=="undefined")return;const{createdTime:i,expire:n}=s[r],a=n||0;s[r]=s[r]&&s[r].value,a!==0&&e-i>a&&(delete s[r],t&&t(r))}),s},O=(s,t)=>s&&s.value?(s.expire=s.expire||t,s.createdTime=Date.now(),s):{value:s,expire:t,createdTime:Date.now()},q=(s,t,e)=>{if(typeof s=="string")return{[s]:O(t,e)};{const r={};return Object.keys(s).forEach(i=>r[i]=O(s[i],e)),r}},v=s=>Array.isArray(s)?s:[s],A={dbName:"localStore",version:1,desc:"localstoredb-v1.3.0",size:5*1024*1024,expire:0,storageType:"local"};class h{constructor(t=A){c(this,"type",this.constructor.type);c(this,"dbName","");c(this,"version",1);c(this,"expire",0);c(this,"desc","");c(this,"size",0);c(this,"storageType","");c(this,"tableName");c(this,"table",{});c(this,"cbLists",{});Object.assign(this,A,t),this.tableName=this.dbName+this.version}select(t){const e=this.getStore(),r={};return t.forEach(i=>r[i]=e[i]),r}upsert(t){const e=this.getStore();return Object.keys(t).forEach(r=>{var i,n;if(this.cbLists[r]){const a=(i=t[r])==null?void 0:i.value,u=(n=e[r])==null?void 0:n.value;JSON.stringify(u)!==JSON.stringify(a)&&this.cbLists[r].forEach(f=>{f(a,u)})}e[r]=t[r]}),this.setStore(JSON.parse(JSON.stringify(e))),!0}delete(t){const e=this.getStore();return t.forEach(r=>delete e[r]),this.setStore(e),!0}deleteAll(){return this.setStore({}),!0}getStore(){return this.table}setStore(t){this.table=t}getItem(t,e){return this.type==="jsonStorage"&&e&&typeof e=="function"&&(this.cbLists[t]&&this.cbLists[t].length?this.cbLists[t]=this.cbLists[t].concat(e):this.cbLists[t]=new Array(e)),Promise.resolve(this.select(v(t))).then(r=>x(r,this.removeItem.bind(this))[t])}setItem(t,e){return Promise.resolve(this.upsert(q(t,e,this.expire)))}removeItem(t){return Promise.resolve(this.delete(v(t)))}removeAll(){return Promise.resolve(this.deleteAll())}getKeys(){return Promise.resolve(this.getStore()).then(t=>Object.keys(t))}getAll(){return Promise.resolve(this.getStore()).then(t=>x(JSON.parse(JSON.stringify(t)),this.removeItem.bind(this)))}isSupported(t=!0){return t&&(typeof window=="undefined"||typeof document=="undefined")?!0:!!(window&&this.hasStore())}hasStore(){return!1}isEqual(t){return this.tableName==t.tableName&&this.type==t.type}static stringify(t){return y(t)}static parse(t){return g(t)}static _add(t){this._all=this._all||[],this._all.push(t)}static matchingInstance(t){const e=this._all||[],r=e.length;for(let i=0;i<r;i++)if(e[i].isEqual(t))return e[i];return this._add(t),t}}c(h,"type"),c(h,"_all");class m extends h{constructor(t){return super(t),this.constructor.matchingInstance(this)}select(t){const e={};return t.forEach(r=>{const i=this.constructor.parse(this.storage().getItem(this.tableName+"/"+r));i!==null&&(e[r]=i)}),e}upsert(t){for(const e in t)this.storage().setItem(this.tableName+"/"+e,this.constructor.stringify(t[e]));return!0}delete(t){return t.map(e=>this.storage().removeItem(this.tableName+"/"+e)),!0}deleteAll(){return Object.keys(this.storage()).forEach(t=>{t.indexOf(this.tableName)===0&&this.storage().removeItem(t)}),!0}getStore(){return this.select(Object.keys(this.storage()).map(t=>{if(t.indexOf(this.tableName)===0)return t.slice(this.tableName.length+1)}).filter(t=>typeof t!="undefined"))}storage(){return this.checkStorageType()}hasStore(){return!!this.checkStorageType()}checkStorageType(){return this.storageType==="local"?window.localStorage:window.sessionStorage}static get type(){return"storage"}}class S extends h{constructor(e){super(e);c(this,"dict",{wechat:{mini:()=>wx,type:"1"},alipay:{mini:()=>my,type:"2"},toutiao:{mini:()=>tt,type:"1"},baidu:{mini:()=>swan,type:"1"}});return this.constructor.matchingInstance(this)}select(e){const r={};return e.forEach(i=>{var a,u;let n="";switch((a=this.dict[this.storageType])==null?void 0:a.type){case"1":n=this.constructor.parse(this.storage().getStorageSync(this.tableName+"/"+i));break;case"2":n=this.constructor.parse((u=this.storage().getStorageSync({key:this.tableName+"/"+i}))==null?void 0:u.data);break}n!==null&&(r[i]=n)}),r}upsert(e){var r;for(const i in e)switch((r=this.dict[this.storageType])==null?void 0:r.type){case"1":this.storage().setStorageSync(this.tableName+"/"+i,this.constructor.stringify(e[i]));break;case"2":this.storage().setStorageSync({key:this.tableName+"/"+i,data:this.constructor.stringify(e[i])});break}return!0}delete(e){return e.map(r=>{var i;switch((i=this.dict[this.storageType])==null?void 0:i.type){case"1":this.storage().removeStorageSync(this.tableName+"/"+r);break;case"2":this.storage().removeStorageSync({key:this.tableName+"/"+r});break}}),!0}deleteAll(){var r;return(((r=this.storage().getStorageInfoSync())==null?void 0:r.keys)||[]).forEach(i=>{var n;if(i.indexOf(this.tableName)===0)switch((n=this.dict[this.storageType])==null?void 0:n.type){case"1":this.storage().removeStorageSync(i);break;case"2":this.storage().removeStorageSync({key:i});break}}),!0}getStore(){var r;const e=((r=this.storage().getStorageInfoSync())==null?void 0:r.keys)||[];return this.select(e.map(i=>{if(i.indexOf(this.tableName)===0)return i.slice(this.tableName.length+1)}).filter(i=>typeof i!="undefined"))}storage(){return this.checkStorageType()}hasStore(){return!!this.checkStorageType()}checkStorageType(){var e;if(!this.dict[this.storageType])throw Error(`没有找到指定小程序: “${this.storageType}”(支持类型列表:${Object.keys(this.dict).join("|")})`);return((e=this.dict[this.storageType])==null?void 0:e.mini())||""}static get type(){return"miniprogram"}}class b extends h{constructor(e){super(e);c(this,"store");return this.constructor.matchingInstance(this)}select(e){const r={},i=[];return e.forEach(n=>i.push(this.transactionStore("readonly","get",n,"").then(a=>r[n]=a))),Promise.all(i).then(()=>r)}upsert(e){const r=[];for(let i in e)r.push(this.transactionStore("readwrite","put",e[i],i));return Promise.all(r).then(()=>!0)}delete(e){const r=[];return e.forEach(i=>r.push(this.transactionStore("readwrite","delete",i,""))),Promise.all(r).then(()=>!0)}deleteAll(){return this.transactionStore("readwrite","clear",void 0,"")}transactionStore(e,r,...i){const n=this;return this.store=this.store||this.createStore(n.tableName),this.store.then(a=>new Promise((u,f)=>{const j=a.transaction(n.tableName,e).objectStore(n.tableName),$=j[r].call(j,...i);$.onsuccess=E=>u(E.target.result),$.onerror=E=>f(E.error)}))}getStore(){return this.transactionStore("readonly","getAllKeys",void 0,"").then(this.select.bind(this))}createStore(e){return new Promise((r,i)=>{const n=window.indexedDB.open(e,1);n.onupgradeneeded=()=>{n.result.createObjectStore(e)},n.onsuccess=()=>r(n.result),n.onerror=()=>i(n.error)})}hasStore(){return!!window.indexedDB}static get type(){return"indexedDB"}}const R="[^0-9a-zA-Z_]",D=new RegExp(R,"g");class d extends h{constructor(e){super(e);c(this,"_store");if(D.test(this.dbName))throw Error(`dbName:${this.dbName},包含非法字符,只支持字母、数字、下划线,请修改!`);return this.constructor.matchingInstance(this)}parsedData(){}select(e){const r=e.map(()=>"?").join(", ");return this.execSql(`SELECT key, value FROM ${this.tableName} WHERE key in (${r})`,e)}upsert(e){return this.getWebsql().transaction(r=>{for(let i in e)r.executeSql(`INSERT OR REPLACE INTO ${this.tableName}(key, value) VALUES (?, ?)`,[i,this.constructor.stringify(e[i])])}),!0}delete(e){const r=e.map(()=>"?").join(", ");return this.execSql(`DELETE FROM ${this.tableName} WHERE key in (${r})`,e),!0}deleteAll(){return this.execSql(`DELETE FROM ${this.tableName}`),!0}getStore(){return this.execSql(`SELECT key, value FROM ${this.tableName}`)}hasStore(){return!!window.openDatabase}getWebsql(){return this._store?this._store:(this._store=window.openDatabase(this.dbName,1,this.desc,this.size),this.execSql(`CREATE TABLE IF NOT EXISTS ${this.tableName} (key unique, value)`),this._store)}execSql(e,r=[]){const i=this;return new Promise(n=>{i.getWebsql().transaction(function(a){a.executeSql(e,r,(u,f)=>{n(i.parseResults(f))})})})}parseResults(e){const r={},i=e.rows.length;for(let n=0;n<i;n++)r[e.rows.item(n).key]=this.constructor.parse(e.rows.item(n).value);return r}static get type(){return"webSql"}}const P=new Date(0).toUTCString(),T="%3D",_=new RegExp(T,"g");class w extends h{constructor(t){return super(t),this.constructor.matchingInstance(this)}upsert(t){for(let e in t)this.setStore(`${this.tableName}/${e}=${this.constructor.stringify(t[e]).replace(/=/g,T)}; path=/`);return!0}delete(t){return t.forEach(e=>this.setStore(`${this.tableName}/${e}=; expires=${P}; path=/`)),!0}deleteAll(){return this.getKeys().then(this.delete.bind(this))}getStore(){let t=document.cookie,e={};return t.split("; ").forEach(r=>{let[i,n]=r.split("=");i.indexOf(this.tableName)===0&&(e[i.slice(this.tableName.length+1)]=this.constructor.parse(n.replace(_,"=")))}),e}setStore(t){document.cookie=t}hasStore(){return typeof document.cookie!="undefined"}static get type(){return"cookies"}}class N extends h{constructor(t){return super(t),this.constructor.matchingInstance(this)}hasStore(){return!0}static get type(){return"jsonStorage"}}const I={[m.type]:m,[S.type]:S,[b.type]:b,[d.type]:d,[w.type]:w,[N.type]:N};function k(s=[],t={}){s&&s.length||(s=[m.type,S.type,b.type,N.type,d.type,w.type]);for(let e=0;e<s.length;e++){let r=I[s[e]];if(r){const i=new r(t);if(i.isSupported())return console.log(`使用储存类型: “${i.type}”`),i}}throw Error(`没有找到指定储存类型: “${s}”(支持类型列表:${Object.keys(I).join("|")})`)}function B(s){const t=typeof s=="string"?[s]:(s||{}).storeType;return k(t,typeof s=="string"?{}:s)}return B});