2026-01-13 14:49:19 +01:00

58 lines
2.0 KiB
TypeScript

import { createIndexedDBHelper, type IndexedDBHelper } from '../helpers/indexedDBHelper'
import type { ObjectType } from './types'
const DB_PREFIX = 'nostr_objects_'
const DB_VERSION = 3 // Incremented to add published field
const STORE_NAME = 'objects'
export function createDbHelperForObjectType(objectType: ObjectType): IndexedDBHelper {
return createIndexedDBHelper({
dbName: `${DB_PREFIX}${objectType}`,
version: DB_VERSION,
storeName: STORE_NAME,
keyPath: 'id',
indexes: getObjectCacheIndexes(),
onUpgrade: (_db: IDBDatabase, event: IDBVersionChangeEvent): void => {
handleObjectCacheUpgrade(event)
},
})
}
export function getRequiredDbHelper(map: Map<ObjectType, IndexedDBHelper>, objectType: ObjectType): IndexedDBHelper {
const helper = map.get(objectType)
if (!helper) {
throw new Error(`Database helper not found for ${objectType}`)
}
return helper
}
function getObjectCacheIndexes(): Array<{ name: string; keyPath: string; unique: boolean }> {
return [
{ name: 'hash', keyPath: 'hash', unique: false },
{ name: 'hashId', keyPath: 'hashId', unique: false },
{ name: 'version', keyPath: 'version', unique: false },
{ name: 'index', keyPath: 'index', unique: false },
{ name: 'hidden', keyPath: 'hidden', unique: false },
{ name: 'cachedAt', keyPath: 'cachedAt', unique: false },
{ name: 'published', keyPath: 'published', unique: false },
]
}
function handleObjectCacheUpgrade(event: IDBVersionChangeEvent): void {
const target = event.target as IDBOpenDBRequest
const { transaction } = target
if (!transaction) {
return
}
const store = transaction.objectStore(STORE_NAME)
ensureIndex(store, 'hash', 'hash')
ensureIndex(store, 'index', 'index')
ensureIndex(store, 'published', 'published')
}
function ensureIndex(store: IDBObjectStore, name: string, keyPath: string): void {
if (!store.indexNames.contains(name)) {
store.createIndex(name, keyPath, { unique: false })
}
}