From 38566f4cd6fc88925b112cb4e6d848cb32df24d7 Mon Sep 17 00:00:00 2001 From: renxia Date: Sat, 23 Dec 2023 10:52:34 +0800 Subject: [PATCH] =?UTF-8?q?wip(LiteStorage):=20=E5=A2=9E=E5=8A=A0=20getIte?= =?UTF-8?q?m=E3=80=81setItem=E3=80=81removeItem=20=E7=AD=89=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E6=8F=90=E4=BE=9B=E4=B8=8E=20localStorage=20?= =?UTF-8?q?=E4=B8=80=E8=87=B4=E7=9A=84=E6=8E=A5=E5=8F=A3=E7=94=A8=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/node/LiteStorage.ts | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/node/LiteStorage.ts b/src/node/LiteStorage.ts index 063584e..ceb9819 100644 --- a/src/node/LiteStorage.ts +++ b/src/node/LiteStorage.ts @@ -25,9 +25,9 @@ export interface LSOptions> { * 轻量的本地文件持久性数据存储。主要用于简单的配置信息持久化 */ export class LiteStorage> { - private static instance: LiteStorage; + private static instance: LiteStorage; static getInstance(options?: LSOptions) { - if (!LiteStorage.instance) LiteStorage.instance = new LiteStorage(options); + if (!LiteStorage.instance) LiteStorage.instance = new LiteStorage(options); return LiteStorage.instance as LiteStorage; } private get cachePath() { @@ -66,6 +66,9 @@ export class LiteStorage> { }, }; } + public get length() { + return Object.keys(this.get(true)).length; + } public get config() { return { ...this.options }; } @@ -93,7 +96,6 @@ export class LiteStorage> { let localCache: LSCache; if (this.isToml) { const TOML = await import('@iarna/toml'); - // localCache = TOML.default.parse(content, '\n', false) as never; localCache = JSON.parse(JSON.stringify(TOML.default.parse(content))); } else { localCache = JSON.parse(content) as LSCache; @@ -121,12 +123,13 @@ export class LiteStorage> { return this; } public get(raw = false) { - const info = this.cache.data[this.options.uuid]; + const info = this.cache.data[this.options.uuid] || {}; return raw ? info : { ...info }; } public getAll() { return this.cache; } + /** 移除一项数据 */ public del(key: keyof T) { const info = this.cache.data[this.options.uuid]; if (key in info) { @@ -135,6 +138,26 @@ export class LiteStorage> { } return this; } + public setItem(key: K, value: Partial, mode: 'merge' | 'cover' = 'merge') { + const data = this.get(true); + if (mode === 'cover') data[key] = value as T[K]; + else assign(data, { [key]: value }); + + return this.set(data, 'cover'); + } + public getItem(key: keyof T) { + const value = this.get(true)[key]; + if (value && typeof value === 'object') return assign({}, value) as T[keyof T]; + return value; + } + /** 移除一项数据。同 del 方法 */ + public removeItem(key: keyof T) { + return this.del(key); + } + /** + * 清理缓存 + * @param isAll 是否清空全部缓存(即移除缓存文件重新初始化)。默认为 false,只清空当前 uuid 约束下的缓存数据 + */ public clear(isAll = false) { if (isAll) { if (fs.existsSync(this.cachePath)) fs.rmSync(this.cachePath, { force: true });