localstoredb
Version:
本地储存工具包,可设置存储时间,支持web和小程序
544 lines (543 loc) • 15.1 kB
JavaScript
var $ = Object.defineProperty;
var j = (s, t, e) => t in s ? $(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
var o = (s, t, e) => (j(s, typeof t != "symbol" ? t + "" : t, e), e);
const L = Object.prototype.toString, u = "2658236dccf04bd49c2aec9136fcf88c";
function q(s, t) {
return new Blob([new Uint8Array(s.split(",")).buffer], { type: t });
}
function R(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 f = (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(u) > 0) {
const [e, r, i] = s.split(u);
e === "ArrayBuffer" ? t = new Uint8Array(r.split(",").map((n) => parseInt(n))).buffer : e === "Blob" ? t = q(i, r) : t = new window[e](r.split(","));
} else if (Array.isArray(s))
t = [], s.forEach((e, r) => {
t[r] = f(e);
});
else if (typeof s == "object") {
if (s === null)
return null;
t = {};
for (const e in s)
t[e] = f(s[e]);
}
return t;
}, g = (s) => {
if (typeof s != "object")
return JSON.stringify(s);
if (s === null)
return "null";
if (Array.isArray(s))
return JSON.stringify(s.map((e) => g(e)));
const t = L.call(s).slice(8, -1);
if (t === "Object") {
let e = {};
for (let r in s)
e[r] = g(s[r]);
return JSON.stringify(e);
} else
t === "ArrayBuffer" ? s = new Uint8Array(s) : t === "Blob" && (s = s.type + u + R(s));
return t + u + 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], c = n || 0;
s[r] = s[r] && s[r].value, c !== 0 && e - i > c && (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()
}, D = (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,
// 过期时间,0 不过期,单位ms
storageType: "local"
// storage下默认local
};
class l {
constructor(t = A) {
o(this, "type", this.constructor.type);
o(this, "dbName", "");
o(this, "version", 1);
o(this, "expire", 0);
o(this, "desc", "");
o(this, "size", 0);
o(this, "storageType", "");
o(this, "tableName");
o(this, "table", {});
// 收集get回调
o(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 c = (i = t[r]) == null ? void 0 : i.value, a = (n = e[r]) == null ? void 0 : n.value;
JSON.stringify(a) !== JSON.stringify(c) && this.cbLists[r].forEach((h) => {
h(c, a);
});
}
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(D(t, e, this.expire)));
}
// 删除
removeItem(t) {
return Promise.resolve(this.delete(v(t)));
}
// 删除全部
removeAll() {
return Promise.resolve(this.deleteAll());
}
// 查询所有key值
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 g(t);
}
static parse(t) {
return f(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;
}
}
o(l, "type"), // 每个存储一个实例
o(l, "_all");
class y extends l {
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 l {
constructor(e) {
super(e);
o(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 c, a;
let n = "";
switch ((c = this.dict[this.storageType]) == null ? void 0 : c.type) {
case "1":
n = this.constructor.parse(this.storage().getStorageSync(this.tableName + "/" + i));
break;
case "2":
n = this.constructor.parse((a = this.storage().getStorageSync({
key: this.tableName + "/" + i
})) == null ? void 0 : a.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 m extends l {
constructor(e) {
super(e);
o(this, "store");
return this.constructor.matchingInstance(this);
}
select(e) {
const r = {}, i = [];
return e.forEach(
(n) => i.push(this.transactionStore("readonly", "get", n, "").then((c) => r[n] = c))
), 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(
(c) => new Promise((a, h) => {
const N = c.transaction(n.tableName, e).objectStore(n.tableName), E = N[r].call(N, ...i);
E.onsuccess = (p) => a(p.target.result), E.onerror = (p) => h(p.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 P = "[^0-9a-zA-Z_]", _ = new RegExp(P, "g");
class b extends l {
constructor(e) {
super(e);
o(this, "_store");
if (_.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(c) {
c.executeSql(e, r, (a, h) => {
n(i.parseResults(h));
});
});
});
}
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 k = new Date(0).toUTCString(), I = "%3D", B = new RegExp(I, "g");
class d extends l {
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, I)}; path=/`
);
return !0;
}
delete(t) {
return t.forEach((e) => this.setStore(`${this.tableName}/${e}=; expires=${k}; 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(B, "=")));
}), e;
}
setStore(t) {
document.cookie = t;
}
hasStore() {
return typeof document.cookie != "undefined";
}
static get type() {
return "cookies";
}
}
class w extends l {
constructor(t) {
return super(t), this.constructor.matchingInstance(this);
}
hasStore() {
return !0;
}
static get type() {
return "jsonStorage";
}
}
const T = {
[y.type]: y,
[S.type]: S,
[m.type]: m,
[b.type]: b,
[d.type]: d,
[w.type]: w
};
function J(s = [], t = {}) {
s && s.length || (s = [
y.type,
S.type,
m.type,
w.type,
b.type,
d.type
]);
for (let e = 0; e < s.length; e++) {
let r = T[s[e]];
if (r) {
const i = new r(t);
if (i.isSupported())
return console.log(`使用储存类型: “${i.type}”`), i;
}
}
throw Error(`没有找到指定储存类型: “${s}”(支持类型列表:${Object.keys(T).join("|")})`);
}
function C(s) {
const t = typeof s == "string" ? [s] : (s || {}).storeType;
return J(t, typeof s == "string" ? {} : s);
}
export {
C as default
};