import { IStorageAdapter } from './IStorageAdapter'; /** * Cordova 存储适配器 * 使用 cordova-plugin-nativestorage */ export class CordovaStorageAdapter implements IStorageAdapter { private NativeStorage: any; private isReady = false; private readyPromise: Promise | null = null; constructor() { this.initializePlugin(); } private initializePlugin() { // 先尝试获取插件 // @ts-ignore this.NativeStorage = window.NativeStorage; if (this.NativeStorage) { this.isReady = true; } else { // 如果插件还没加载,监听 deviceready 事件 document.addEventListener('deviceready', () => { // @ts-ignore this.NativeStorage = window.NativeStorage; this.isReady = !!this.NativeStorage; if (!this.isReady) { console.warn('NativeStorage plugin still not available after deviceready'); } }, false); } } private async ensureReady(): Promise { if (this.isReady) { return; } // 如果还没准备好,创建一个等待 Promise if (!this.readyPromise) { this.readyPromise = new Promise((resolve, reject) => { const checkReady = () => { if (this.isReady) { resolve(); } else { // 每100ms检查一次,最多等待10秒 setTimeout(checkReady, 100); } }; // 10秒超时 setTimeout(() => { if (!this.isReady) { reject(new Error('NativeStorage plugin initialization timeout')); } }, 10000); checkReady(); }); } return this.readyPromise; } async getItem(key: string): Promise { await this.ensureReady(); return new Promise((resolve) => { this.NativeStorage.getItem( key, (value: string) => resolve(value), (error: any) => { console.error('读取存储失败:', error); resolve(null); } ); }); } async setItem(key: string, value: string): Promise { await this.ensureReady(); return new Promise((resolve, reject) => { this.NativeStorage.setItem( key, value, () => resolve(), (error: any) => { console.error('保存存储失败:', error); reject(error); } ); }); } async removeItem(key: string): Promise { await this.ensureReady(); return new Promise((resolve, reject) => { this.NativeStorage.remove( key, () => resolve(), (error: any) => { console.error('删除存储失败:', error); reject(error); } ); }); } }