92 lines
2.5 KiB
TypeScript
92 lines
2.5 KiB
TypeScript
import { createIndexedDBHelper, type IndexedDBHelper } from './helpers/indexedDBHelper'
|
|
|
|
const DB_NAME = 'nostr_paywall_settings'
|
|
const DB_VERSION = 3
|
|
const STORE_NAME = 'search_history'
|
|
|
|
export interface SearchHistoryItem {
|
|
query: string
|
|
timestamp: number
|
|
}
|
|
|
|
const MAX_HISTORY_ITEMS = 10
|
|
|
|
class SearchHistoryService {
|
|
private readonly dbHelper: IndexedDBHelper
|
|
|
|
constructor() {
|
|
this.dbHelper = createIndexedDBHelper({
|
|
dbName: DB_NAME,
|
|
version: DB_VERSION,
|
|
storeName: STORE_NAME,
|
|
keyPath: 'query',
|
|
indexes: [{ name: 'timestamp', keyPath: 'timestamp', unique: false }],
|
|
})
|
|
}
|
|
|
|
async saveSearchQuery(query: string): Promise<void> {
|
|
if (!query.trim()) {
|
|
return
|
|
}
|
|
try {
|
|
const trimmedQuery = query.trim()
|
|
const existing = await this.dbHelper.get<SearchHistoryItem>(trimmedQuery)
|
|
if (existing) {
|
|
await this.dbHelper.delete(trimmedQuery)
|
|
}
|
|
await this.dbHelper.put({ query: trimmedQuery, timestamp: Date.now() })
|
|
await this.limitHistorySize()
|
|
} catch (error) {
|
|
console.error('Error saving search history:', error)
|
|
}
|
|
}
|
|
|
|
async getSearchHistory(): Promise<SearchHistoryItem[]> {
|
|
try {
|
|
const items = await this.dbHelper.getAll<SearchHistoryItem>()
|
|
const sorted = items.sort((a, b) => b.timestamp - a.timestamp)
|
|
return sorted.slice(0, MAX_HISTORY_ITEMS)
|
|
} catch (error) {
|
|
console.error('Error getting search history:', error)
|
|
return []
|
|
}
|
|
}
|
|
|
|
async clearSearchHistory(): Promise<void> {
|
|
try {
|
|
await this.dbHelper.clear()
|
|
} catch (error) {
|
|
console.error('Error clearing search history:', error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
private async limitHistorySize(): Promise<void> {
|
|
try {
|
|
const history = await this.getSearchHistory()
|
|
if (history.length > MAX_HISTORY_ITEMS) {
|
|
const toDelete = history.slice(MAX_HISTORY_ITEMS)
|
|
for (const item of toDelete) {
|
|
await this.dbHelper.delete(item.query)
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('Error limiting history size:', error)
|
|
}
|
|
}
|
|
}
|
|
|
|
const searchHistoryService = new SearchHistoryService()
|
|
|
|
export async function saveSearchQuery(query: string): Promise<void> {
|
|
return searchHistoryService.saveSearchQuery(query)
|
|
}
|
|
|
|
export async function getSearchHistory(): Promise<SearchHistoryItem[]> {
|
|
return searchHistoryService.getSearchHistory()
|
|
}
|
|
|
|
export async function clearSearchHistory(): Promise<void> {
|
|
return searchHistoryService.clearSearchHistory()
|
|
}
|