2024-05-30 22:26:57 +05:00
|
|
|
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)
|
|
|
|
}
|
2024-05-31 14:26:59 +05:00
|
|
|
|
|
|
|
// Method to clear cache data
|
|
|
|
public async clearCacheData() {
|
|
|
|
// Clear the 'userMetadata' store in the IndexedDB database
|
|
|
|
await this.db.clear('userMetadata')
|
|
|
|
|
|
|
|
// Reload the current page to ensure any cached data is reset
|
|
|
|
window.location.reload()
|
|
|
|
}
|
2024-05-30 22:26:57 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Export the single instance of LocalCache
|
|
|
|
export const localCache = await LocalCache.getInstance()
|