stuffs
This commit is contained in:
60
src/storage/baseStorage.ts
Normal file
60
src/storage/baseStorage.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import Dexie from 'dexie'
|
||||
|
||||
export class BaseStorage<T extends { id: string }> {
|
||||
protected dexie: Dexie
|
||||
protected tableName: string
|
||||
|
||||
constructor(tableName: string, schema: string) {
|
||||
this.tableName = tableName
|
||||
this.dexie = new Dexie(tableName)
|
||||
this.dexie.version(1).stores({
|
||||
[tableName]: schema
|
||||
})
|
||||
}
|
||||
|
||||
async add(item: T, overwrite = false) {
|
||||
try {
|
||||
const existing = await this.get(item.id)
|
||||
if (existing && !overwrite) return
|
||||
|
||||
await this.dexie.table(this.tableName).put({ ...item })
|
||||
} catch (error) {
|
||||
console.error(`Failed to add ${this.tableName} ${item.id}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
async get(id: string): Promise<T | null> {
|
||||
try {
|
||||
const item = await this.dexie.table(this.tableName).get(id)
|
||||
return item || null
|
||||
} catch (error) {
|
||||
console.error(`Failed to retrieve ${this.tableName} ${id}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async getAll(): Promise<T[]> {
|
||||
try {
|
||||
return await this.dexie.table(this.tableName).toArray()
|
||||
} catch (error) {
|
||||
console.error(`Failed to retrieve all ${this.tableName}:`, error)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async reset() {
|
||||
try {
|
||||
await this.dexie.table(this.tableName).clear()
|
||||
} catch (error) {
|
||||
console.error(`Failed to clear ${this.tableName}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
try {
|
||||
await this.dexie.delete()
|
||||
} catch (error) {
|
||||
console.error(`Failed to destroy ${this.tableName}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user