zL1ghT_

IdexedDB Abstractation

May 2nd, 2021
147
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { openDB as openConnection, IDBPDatabase, DBSchema } from 'idb';
  2.  
  3. interface Schema extends DBSchema {
  4.     'completed': {
  5.         key: string;
  6.         value: boolean;
  7.     };
  8. }
  9.  
  10. // type Names<Schema extends Object> =  keyof Schema;
  11.  
  12. class IndexedDB {
  13.     private static _instance: IndexedDB | null = null;
  14.     private _database!: IDBPDatabase<Schema>;
  15.  
  16.     private constructor() {}
  17.  
  18.     public static get instance(): IndexedDB {
  19.         if (IndexedDB._instance === null) {
  20.             IndexedDB._instance = new IndexedDB();
  21.         }
  22.         return IndexedDB._instance;
  23.     }
  24.  
  25.     public async connect() {
  26.         if(this._database === undefined) {
  27.             this._database = await openConnection<Schema>('advancements_', 1, {
  28.                 upgrade(db: IDBPDatabase<Schema>) {
  29.                     if (!db.objectStoreNames.contains('completed')) {
  30.                         db.createObjectStore('completed', { keyPath: '_id' });
  31.                     }
  32.                 }
  33.             });
  34.         }
  35.  
  36.         return this._database;
  37.     }
  38. }
  39.  
  40. export default IndexedDB;
RAW Paste Data