- Cache queries and songs across mobile and web - Show cached content and skeletons during loading - Move shared playback and cache utilities into Convex client
68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
|
|
import {
|
|
configurePersistentCache,
|
|
type PersistentCacheBackend,
|
|
type PersistentCacheEntry,
|
|
} from "@otunes/convex/client/persistent-cache"
|
|
|
|
export * from "@otunes/convex/client/persistent-cache"
|
|
|
|
const KEY_PREFIX = "otunes-cache:"
|
|
const READ_BATCH_SIZE = 200
|
|
|
|
async function cacheStorageKeys() {
|
|
const keys = await AsyncStorage.getAllKeys()
|
|
return keys.filter((key) => key.startsWith(KEY_PREFIX))
|
|
}
|
|
|
|
const asyncStorageBackend: PersistentCacheBackend = {
|
|
async loadAll() {
|
|
const keys = await cacheStorageKeys()
|
|
const entries: Array<[string, PersistentCacheEntry]> = []
|
|
for (let start = 0; start < keys.length; start += READ_BATCH_SIZE) {
|
|
const pairs = await AsyncStorage.multiGet(
|
|
keys.slice(start, start + READ_BATCH_SIZE)
|
|
)
|
|
for (const [storageKey, raw] of pairs) {
|
|
if (!raw) continue
|
|
try {
|
|
entries.push([
|
|
storageKey.slice(KEY_PREFIX.length),
|
|
JSON.parse(raw) as PersistentCacheEntry,
|
|
])
|
|
} catch {
|
|
// Skip entries that were cut off mid-write.
|
|
}
|
|
}
|
|
}
|
|
return entries
|
|
},
|
|
|
|
async write(writes) {
|
|
const sets: [string, string][] = []
|
|
const removes: string[] = []
|
|
for (const [key, entry] of writes) {
|
|
if (entry === null) {
|
|
removes.push(KEY_PREFIX + key)
|
|
} else {
|
|
sets.push([KEY_PREFIX + key, JSON.stringify(entry)])
|
|
}
|
|
}
|
|
await Promise.all([
|
|
sets.length > 0 ? AsyncStorage.multiSet(sets) : null,
|
|
removes.length > 0 ? AsyncStorage.multiRemove(removes) : null,
|
|
])
|
|
},
|
|
|
|
async clear() {
|
|
await AsyncStorage.multiRemove(await cacheStorageKeys())
|
|
},
|
|
}
|
|
|
|
// Android's AsyncStorage database is capped at 6 MB by default, so keep fewer
|
|
// entries than the web cache.
|
|
configurePersistentCache(asyncStorageBackend, {
|
|
maxEntriesByPrefix: { q: 200, song: 3000, files: 500 },
|
|
})
|