The class is named DataStore and takes two parameters in the constructor: dbName (the name of the IndexedDB database) and storeName (the name of the object store within the database).
The init method is used to initialize the class. It checks if IndexedDB is supported by calling the isIndexedDBSupported method. If supported, it opens the database using the openDB function from the idb library and creates an object store with the specified storeName if it doesn't already exist.
The isIndexedDBSupported method checks if the indexedDB property exists in the window object to determine if IndexedDB is supported by the browser.
The class provides methods that mimic the localStorage API:
getItem(key): Retrieves the value associated with the specified key from either IndexedDB or localStorage.
setItem(key, value): Stores a key-value pair in either IndexedDB or localStorage.
removeItem(key): Removes the value associated with the specified key from either IndexedDB or localStorage.
clear(): Clears all key-value pairs from either IndexedDB or localStorage.
key(index): Retrieves the key at the specified index from either IndexedDB or localStorage.
length(): Returns the number of key-value pairs stored in either IndexedDB or localStorage.
The class uses async/await syntax to handle asynchronous operations with IndexedDB.
If IndexedDB is not supported, the class falls back to using localStorage for storing and retrieving data.
To use this class, you need to import it into your frontend code (e.g., React or Vue.js) and create an instance of the DataStore class with the desired database name and store name. Make sure to call the init method before using any other methods of the class.
Note: Make sure to install the idb library using npm or include it in your project before using this code.