89 lines
2.4 KiB
TypeScript
89 lines
2.4 KiB
TypeScript
/**
|
|
* IndexedDB cache for application settings (excluding keys)
|
|
* Stores settings and last sync date for background synchronization
|
|
*/
|
|
|
|
import { createIndexedDBHelper, type IndexedDBHelper } from './helpers/indexedDBHelper'
|
|
|
|
const DB_NAME = 'nostr_paywall_settings'
|
|
const DB_VERSION = 1
|
|
const STORE_NAME = 'settings'
|
|
|
|
export interface SettingsData {
|
|
// Settings excluding keys (relays, NIP-95 APIs, etc.)
|
|
relays?: Array<{ id: string; url: string; enabled: boolean; priority: number; createdAt: number }>
|
|
nip95Apis?: Array<{ id: string; url: string; enabled: boolean; priority: number; createdAt: number }>
|
|
platformLightningAddress?: string
|
|
// Last sync date (Unix timestamp) for background synchronization
|
|
lastSyncDate?: number
|
|
// Metadata
|
|
updatedAt: number
|
|
}
|
|
|
|
class SettingsCacheService {
|
|
private readonly dbHelper: IndexedDBHelper
|
|
|
|
constructor() {
|
|
this.dbHelper = createIndexedDBHelper({
|
|
dbName: DB_NAME,
|
|
version: DB_VERSION,
|
|
storeName: STORE_NAME,
|
|
keyPath: 'key',
|
|
indexes: [{ name: 'updatedAt', keyPath: 'updatedAt', unique: false }],
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Get settings (excluding keys) and last sync date
|
|
*/
|
|
async getSettings(): Promise<SettingsData | null> {
|
|
try {
|
|
const result = await this.dbHelper.get<{ key: string; value: SettingsData }>('settings')
|
|
return result?.value ?? null
|
|
} catch (error) {
|
|
console.error('Error retrieving settings from cache:', error)
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Save settings (excluding keys) and last sync date
|
|
*/
|
|
async saveSettings(settings: SettingsData): Promise<void> {
|
|
try {
|
|
await this.dbHelper.put({
|
|
key: 'settings',
|
|
value: {
|
|
...settings,
|
|
updatedAt: Date.now(),
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error('Error saving settings to cache:', error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update last sync date
|
|
*/
|
|
async updateLastSyncDate(timestamp: number): Promise<void> {
|
|
const settings = await this.getSettings()
|
|
await this.saveSettings({
|
|
...settings,
|
|
lastSyncDate: timestamp,
|
|
updatedAt: Date.now(),
|
|
} as SettingsData)
|
|
}
|
|
|
|
/**
|
|
* Get last sync date
|
|
*/
|
|
async getLastSyncDate(): Promise<number | null> {
|
|
const settings = await this.getSettings()
|
|
return settings?.lastSyncDate ?? null
|
|
}
|
|
}
|
|
|
|
export const settingsCache = new SettingsCacheService()
|