From 85de9d1e3b29f2d9ed810ecf9d773cc9cc8bf918 Mon Sep 17 00:00:00 2001 From: renxia Date: Wed, 10 Jan 2024 10:32:28 +0800 Subject: [PATCH] =?UTF-8?q?perf(LiteStorage):=20=E5=A2=9E=E5=8A=A0=20ready?= =?UTF-8?q?=20=E6=96=B9=E6=B3=95=EF=BC=8C=E5=A2=9E=E5=8A=A0=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/node/LiteStorage.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/node/LiteStorage.ts b/src/node/LiteStorage.ts index a6a6428..d4f9a5c 100644 --- a/src/node/LiteStorage.ts +++ b/src/node/LiteStorage.ts @@ -1,7 +1,8 @@ import { homedir } from 'node:os'; import { dirname, resolve } from 'node:path'; -import { fs } from './fs-system'; -import { assign, safeJsonParse, safeStringify, tryLoadJSON5 } from '../common/objects'; +import { fs } from './fs-system.js'; +import { assign, safeJsonParse, safeStringify, tryLoadJSON5 } from '../common/objects.js'; +import { Barrier } from '../common/async.js'; export interface LSCache { version: string; @@ -23,6 +24,16 @@ export interface LSOptions> { /** * 轻量的本地文件持久性数据存储。主要用于简单的配置信息持久化 + * @example + * ```ts + * const stor = await new LiteStorage({ uuid: 'test1' }).ready(); + * const config = stor.get(); + * console.log(config); + * stor.getItem('key1'); + * stor.setItem('key2', { a: 1 }); + * stor.removeItem('key2'); + * stor.clear(); + * ``` */ export class LiteStorage> { private static instance: LiteStorage; @@ -33,6 +44,7 @@ export class LiteStorage> { private get cachePath() { return this.options.filepath; } + private barrier = new Barrier(); private isToml = false; private isJson5 = false; @@ -50,7 +62,7 @@ export class LiteStorage> { }; this.init(); - this.reload(); + this.reload().then(() => this.barrier.open()); } private init() { const { filepath = 'ls.json', uuid, version } = this.options; @@ -74,6 +86,10 @@ export class LiteStorage> { public get config() { return { ...this.options }; } + public async ready() { + await this.barrier.wait(); + return this; + } /** 主动保存 */ public async save(value?: T, mode: 'merge' | 'cover' = 'merge') { if (value) return this.set(value, mode);