Created
September 15, 2019 03:22
-
-
Save navio/21ddae7ba9b56fc5ac553621103eeb47 to your computer and use it in GitHub Desktop.
Database Implementation with IndexDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Store,set,get,keys,del } from 'idb-keyval'; | |
| const DBNAME = "PodcastSuite"; | |
| export interface IDBConfig{ | |
| name: string; | |
| database?: string; | |
| } | |
| export abstract class PodcastSuiteDatabase { | |
| constructor(config: IDBConfig){ } | |
| async get(key:string, config: object): Promise<any> { } | |
| async set(key:string, config: object): Promise<any> { } | |
| async del(key:string, config: object): Promise<any> { } | |
| async keys(key:string, config: object): Promise<any> { } | |
| async entries(key:string, config: object): Promise<any> { } | |
| } | |
| export class DataBase extends PodcastSuiteDatabase{ | |
| private static getStore(config: IDBConfig | any){ | |
| const {database, name} = config | |
| return new Store(database, name); | |
| } | |
| private store: Store; | |
| constructor( config: IDBConfig | Store ){ | |
| if(config instanceof Store){ | |
| const name = config.storeName; | |
| super({name}); | |
| this.store = config; | |
| }else{ | |
| super(config); | |
| this.store = DataBase.getStore(config); | |
| } | |
| } | |
| async get(key:string){ | |
| return await get(key,this.store); | |
| } | |
| async set(key:string){ | |
| return await set(key,this.store); | |
| } | |
| async del(key:string){ | |
| return await del(key,this.store); | |
| } | |
| async keys(){ | |
| return await keys(this.store); | |
| } | |
| async entries(){ | |
| const keys = await this.keys(); | |
| return keys.map( (key) => get(key) ); | |
| } | |
| } | |
| const DataBases = new Proxy({db: DBNAME},{ | |
| get(target,prop){ | |
| if(target[prop]){ | |
| return target[prop]; | |
| }else{ | |
| const name = prop.toString(); | |
| const database = new DataBase({ name, database: DBNAME }) | |
| target[prop] = database; | |
| return database; | |
| } | |
| }, | |
| set(){ | |
| throw new Error("Access denied"); | |
| } | |
| }); | |
| export default DataBases; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment