From 67280959f6124331e43d791e991ac0a840713f06 Mon Sep 17 00:00:00 2001 From: abearixong Date: Tue, 9 Dec 2025 09:53:05 +0800 Subject: [PATCH] feat: add storage interface --- src/app.ts | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index afa6edc..302c9ce 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,15 +1,22 @@ import { QueryRouterServer } from '@kevisual/router' import { use } from '@kevisual/context' import { Query } from '@kevisual/query' -import { Kevisual, BailianChat } from '@kevisual/ai' +import { Kevisual } from '@kevisual/ai' import mitt from 'mitt'; const isBrowser = typeof window !== 'undefined' + +export type Storage = { + getItem(key: string): string | null + setItem(key: string, value: string): void + removeItem(key: string): void +} type AppOptions = { router?: QueryRouterServer query?: Query queryOptions?: { url?: string } token?: string initAI?: boolean + storage?: Storage } export class App { #router: QueryRouterServer @@ -19,11 +26,22 @@ export class App { ai!: Kevisual; loading = false; emitter = mitt(); + storage: Storage | null = null; constructor(opts?: AppOptions) { this.#router = opts?.router || new QueryRouterServer() const queryOptions = opts?.queryOptions || {} this.query = opts?.query || new Query({ url: queryOptions.url || 'https://kevisual.cn/api/router' }) const initAI = opts?.initAI ?? true; + if (opts?.storage) { + this.storage = opts.storage; + } else { + if (isBrowser) { + this.storage = sessionStorage; + } else { + console.warn('没有提供 storage,某些功能可能无法使用'); + } + } + if (opts?.token) { this.#token = opts.token if (initAI) { @@ -59,7 +77,8 @@ export class App { } get token() { if (isBrowser && !this.#token) { - this.#token = localStorage.getItem('token') || '' + // 只在浏览器环境下从 localStorage 获取 token + this.#token = localStorage?.getItem('token') || '' return this.#token; } return this.#token; @@ -74,11 +93,9 @@ export class App { this.#router = value; } async getConfig(key: string) { - if (isBrowser) { - const config = sessionStorage.getItem(`config_${key}`) - if (config) { - return Promise.resolve(JSON.parse(config)) - } + const _config = this.storage?.getItem?.(`config_${key}`) + if (_config) { + return Promise.resolve(JSON.parse(_config)) } const res = await this.query.post({ path: 'config', @@ -92,7 +109,7 @@ export class App { const data = res.data || {} const config = data.data || {} if (isBrowser) { - sessionStorage.setItem(`config_${key}`, JSON.stringify(config)) + this.storage?.setItem?.(`config_${key}`, JSON.stringify(config)) } return config; }