CordovaStorageAdapter.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { IStorageAdapter } from './IStorageAdapter';
  2. /**
  3. * Cordova 存储适配器
  4. * 使用 cordova-plugin-nativestorage
  5. */
  6. export class CordovaStorageAdapter implements IStorageAdapter {
  7. private NativeStorage: any;
  8. private isReady = false;
  9. private readyPromise: Promise<void> | null = null;
  10. constructor() {
  11. this.initializePlugin();
  12. }
  13. private initializePlugin() {
  14. // 先尝试获取插件
  15. // @ts-ignore
  16. this.NativeStorage = window.NativeStorage;
  17. if (this.NativeStorage) {
  18. this.isReady = true;
  19. } else {
  20. // 如果插件还没加载,监听 deviceready 事件
  21. document.addEventListener('deviceready', () => {
  22. // @ts-ignore
  23. this.NativeStorage = window.NativeStorage;
  24. this.isReady = !!this.NativeStorage;
  25. if (!this.isReady) {
  26. console.warn('NativeStorage plugin still not available after deviceready');
  27. }
  28. }, false);
  29. }
  30. }
  31. private async ensureReady(): Promise<void> {
  32. if (this.isReady) {
  33. return;
  34. }
  35. // 如果还没准备好,创建一个等待 Promise
  36. if (!this.readyPromise) {
  37. this.readyPromise = new Promise((resolve, reject) => {
  38. const checkReady = () => {
  39. if (this.isReady) {
  40. resolve();
  41. } else {
  42. // 每100ms检查一次,最多等待10秒
  43. setTimeout(checkReady, 100);
  44. }
  45. };
  46. // 10秒超时
  47. setTimeout(() => {
  48. if (!this.isReady) {
  49. reject(new Error('NativeStorage plugin initialization timeout'));
  50. }
  51. }, 10000);
  52. checkReady();
  53. });
  54. }
  55. return this.readyPromise;
  56. }
  57. async getItem(key: string): Promise<string | null> {
  58. await this.ensureReady();
  59. return new Promise((resolve) => {
  60. this.NativeStorage.getItem(
  61. key,
  62. (value: string) => resolve(value),
  63. (error: any) => {
  64. console.error('读取存储失败:', error);
  65. resolve(null);
  66. }
  67. );
  68. });
  69. }
  70. async setItem(key: string, value: string): Promise<void> {
  71. await this.ensureReady();
  72. return new Promise((resolve, reject) => {
  73. this.NativeStorage.setItem(
  74. key,
  75. value,
  76. () => resolve(),
  77. (error: any) => {
  78. console.error('保存存储失败:', error);
  79. reject(error);
  80. }
  81. );
  82. });
  83. }
  84. async removeItem(key: string): Promise<void> {
  85. await this.ensureReady();
  86. return new Promise((resolve, reject) => {
  87. this.NativeStorage.remove(
  88. key,
  89. () => resolve(),
  90. (error: any) => {
  91. console.error('删除存储失败:', error);
  92. reject(error);
  93. }
  94. );
  95. });
  96. }
  97. }