11// src/utils/indexedDB.ts
2- import { openDB , DBSchema } from 'idb' ;
2+ import { openDB , DBSchema , IDBPDatabase } from 'idb' ;
33
44interface DB extends DBSchema {
55 cache : {
@@ -11,34 +11,70 @@ interface DB extends DBSchema {
1111 } ;
1212}
1313
14- const dbPromise = openDB < DB > ( 'minusx-cache-db' , 1 , {
15- upgrade ( db ) {
16- db . createObjectStore ( 'cache' ) ;
17- } ,
18- } ) ;
14+ let dbPromise : Promise < IDBPDatabase < DB > > | null = null ;
15+
16+ const getDB = async ( ) : Promise < IDBPDatabase < DB > > => {
17+ if ( ! dbPromise ) {
18+ dbPromise = openDB < DB > ( 'minusx-cache-db' , 1 , {
19+ upgrade ( db ) {
20+ db . createObjectStore ( 'cache' ) ;
21+ } ,
22+ } ) ;
23+ }
24+
25+ try {
26+ return await dbPromise ;
27+ } catch ( error : any ) {
28+ // Connection failed, reset and retry once
29+ dbPromise = null ;
30+ dbPromise = openDB < DB > ( 'minusx-cache-db' , 1 , {
31+ upgrade ( db ) {
32+ db . createObjectStore ( 'cache' ) ;
33+ } ,
34+ } ) ;
35+ return await dbPromise ;
36+ }
37+ } ;
1938
2039export const setCache = async ( key : string , value : any ) => {
21- const db = await dbPromise ;
22- await db . put ( 'cache' , { data : value , createdAt : Date . now ( ) } , key ) ;
40+ try {
41+ const db = await getDB ( ) ;
42+ await db . put ( 'cache' , { data : value , createdAt : Date . now ( ) } , key ) ;
43+ } catch ( error ) {
44+ // Silently fail - cache write is not critical
45+ }
2346} ;
2447
2548export const getCache = async ( key : string ) => {
26- const db = await dbPromise ;
27- const cachedItem = await db . get ( 'cache' , key ) ;
28- if ( cachedItem ) {
29- return cachedItem ;
49+ try {
50+ const db = await getDB ( ) ;
51+ const cachedItem = await db . get ( 'cache' , key ) ;
52+ if ( cachedItem ) {
53+ return cachedItem ;
54+ }
55+ return null ;
56+ } catch ( error ) {
57+ // Treat any DB error as cache miss
58+ return null ;
3059 }
31- return null ;
3260} ;
3361
3462export const deleteCache = async ( key : string ) => {
35- const db = await dbPromise ;
36- await db . delete ( 'cache' , key ) ;
63+ try {
64+ const db = await getDB ( ) ;
65+ await db . delete ( 'cache' , key ) ;
66+ } catch ( error ) {
67+ // Silently fail - cache delete is not critical
68+ }
3769} ;
3870
3971export const resetCache = async ( ) => {
40- const db = await dbPromise ;
41- const tx = db . transaction ( 'cache' , 'readwrite' ) ;
42- tx . objectStore ( 'cache' ) . clear ( ) ;
43- await tx . done ;
72+ try {
73+ const db = await getDB ( ) ;
74+ const tx = db . transaction ( 'cache' , 'readwrite' ) ;
75+ tx . objectStore ( 'cache' ) . clear ( ) ;
76+ await tx . done ;
77+ } catch ( error ) {
78+ // Silently fail - cache reset is not critical
79+ }
4480} ;
0 commit comments