Created
August 14, 2024 19:50
-
-
Save wanderer20/187c8f67a74f20f71f38585094696c75 to your computer and use it in GitHub Desktop.
IDB
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 {IndexedDBRepository, DB} from "../utils/database.ts"; | |
import {onMounted} from "vue"; | |
interface ExampleObj { | |
name: string | |
files: File[] | |
} | |
interface ExampleDB extends DB { | |
'my-store': { | |
key:number | |
value: ExampleObj | |
} | |
} | |
const files: File[] = [ | |
new File(['content'], 'file1.txt'), | |
new File(['content'], 'file2.txt'), | |
] | |
const obj = { | |
name: 'Example', | |
files | |
} | |
onMounted(async () => { | |
const dbService = new IndexedDBRepository<ExampleDB, 'my-store', ExampleObj>('db-name-test', 'my-store') | |
const obj2 = { | |
...obj | |
} | |
// await dbService.create(obj2) | |
const r = await dbService.read(4) | |
console.log(r) | |
}) |
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 {openDB, IDBPDatabase, DBSchema, StoreNames, StoreValue, StoreKey } from 'idb' | |
export interface DB extends DBSchema { | |
[store: string]: { | |
key: number, | |
value: any | |
} | |
} | |
export class IndexedDBRepository<T extends DB, K extends StoreNames<T>, V extends StoreValue<T, K>> { | |
private dbPromise: Promise<IDBPDatabase<T>>; | |
private storeName: K; | |
constructor(dbName: string, storeName: K) { | |
this.storeName = storeName; | |
this.dbPromise = openDB<T>(dbName, 1, { | |
upgrade(db) { | |
db.createObjectStore(storeName, { | |
keyPath: 'id', | |
autoIncrement: true, | |
}); | |
}, | |
}); | |
} | |
async create(item: V): Promise<StoreKey<T, K>> { | |
const db = await this.dbPromise; | |
return await db.add(this.storeName, item); | |
} | |
async read(id: StoreKey<T, K>): Promise<V | undefined> { | |
const db = await this.dbPromise; | |
return await db.get(this.storeName, id); | |
} | |
async update(item: V): Promise<void> { | |
const db = await this.dbPromise; | |
await db.put(this.storeName, item); | |
} | |
async delete(id: StoreKey<T, K>): Promise<void> { | |
const db = await this.dbPromise; | |
await db.delete(this.storeName, id); | |
} | |
async getAll(): Promise<V[]> { | |
const db = await this.dbPromise; | |
return await db.getAll(this.storeName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment