|
|
@@ -6,17 +6,67 @@ import { IStorageAdapter } from './IStorageAdapter';
|
|
|
*/
|
|
|
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) {
|
|
|
- throw new Error('NativeStorage plugin not available');
|
|
|
+
|
|
|
+ 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,
|
|
|
@@ -30,6 +80,7 @@ export class CordovaStorageAdapter implements IStorageAdapter {
|
|
|
}
|
|
|
|
|
|
async setItem(key: string, value: string): Promise<void> {
|
|
|
+ await this.ensureReady();
|
|
|
return new Promise((resolve, reject) => {
|
|
|
this.NativeStorage.setItem(
|
|
|
key,
|
|
|
@@ -44,6 +95,7 @@ export class CordovaStorageAdapter implements IStorageAdapter {
|
|
|
}
|
|
|
|
|
|
async removeItem(key: string): Promise<void> {
|
|
|
+ await this.ensureReady();
|
|
|
return new Promise((resolve, reject) => {
|
|
|
this.NativeStorage.remove(
|
|
|
key,
|