| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { IStorageAdapter } from './IStorageAdapter';
- /**
- * Cordova 存储适配器
- * 使用 cordova-plugin-nativestorage
- */
- export class CordovaStorageAdapter implements IStorageAdapter {
- private NativeStorage: any;
- private isReady = false;
- private readyPromise: Promise<void> | 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<void> {
- 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<string | null> {
- 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<void> {
- 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<void> {
- await this.ensureReady();
- return new Promise((resolve, reject) => {
- this.NativeStorage.remove(
- key,
- () => resolve(),
- (error: any) => {
- console.error('删除存储失败:', error);
- reject(error);
- }
- );
- });
- }
- }
|