55 lines
1.6 KiB
TypeScript
Raw Normal View History

import { IDBPDatabase, openDB } from 'idb'
import { Event } from 'nostr-tools'
import { CachedMetadataEvent } from '../../types'
import { SchemaV1 } from './schema'
class LocalCache {
// Static property to hold the single instance of LocalCache
private static instance: LocalCache | null = null
private db!: IDBPDatabase<SchemaV1>
// Private constructor to prevent direct instantiation
private constructor() {}
// Method to initialize the database
private async init() {
this.db = await openDB<SchemaV1>('sigit-cache', 1, {
upgrade(db) {
db.createObjectStore('userMetadata', { keyPath: 'event.pubkey' })
}
})
}
// Static method to get the single instance of LocalCache
public static async getInstance(): Promise<LocalCache> {
// If the instance doesn't exist, create it
if (!LocalCache.instance) {
LocalCache.instance = new LocalCache()
await LocalCache.instance.init()
}
// Return the single instance of LocalCache
return LocalCache.instance
}
// Method to add user metadata
public async addUserMetadata(event: Event) {
await this.db.put('userMetadata', { event, cachedAt: Date.now() })
}
// Method to get user metadata by key
public async getUserMetadata(
key: string
): Promise<CachedMetadataEvent | null> {
const data = await this.db.get('userMetadata', key)
return data || null
}
// Method to delete user metadata by key
public async deleteUserMetadata(key: string) {
await this.db.delete('userMetadata', key)
}
}
// Export the single instance of LocalCache
export const localCache = await LocalCache.getInstance()