feat: add storage interface
This commit is contained in:
33
src/app.ts
33
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user