-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBCache.ts
64 lines (59 loc) · 1.92 KB
/
DBCache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import DB from './indexDB'
type DBCacheItem = {
key: string
timestamp: number
blob: Blob
}
export default class DBCache {
private _db: DB
storeName: string
scope = 'app-cache'
version: number
maxEntries?: number
constructor(storeName: string, version: number, options?: { scope: string, maxEntries?: number }) {
this.storeName = storeName
this.version = version
this.maxEntries = options?.maxEntries
if (options?.scope) {
this.scope = options.scope
}
this._db = new DB(storeName, version)
}
async connect() {
const db = await this._db.connect(({ db, transaction }) => {
const objectStore = !db.objectStoreNames.contains(this.scope)
? db.createObjectStore(this.scope)
: transaction?.objectStore(this.scope)
if (objectStore) {
if (!objectStore.indexNames.contains('timestamp')) {
objectStore.createIndex('timestamp', 'timestamp')
}
}
})
return db
}
async set(key: string, data: Blob) {
const result = await this._db.get<DBCacheItem>(this.scope, key)
if (!result && this.maxEntries) {
const items = await this._db.getRange<DBCacheItem>(this.scope, this.maxEntries, -1, { index: 'timestamp' })
for (const item of items) {
this._db.delete(this.scope, item.key)
}
}
await this._db.set(this.scope, key, {
key,
timestamp: new Date().valueOf(),
blob: data
})
}
async get(key: string) {
const result = await this._db.get<DBCacheItem>(this.scope, key)
if (result) {
await this._db.set(this.scope, key, {
timestamp: new Date().valueOf(),
blob: result.blob
})
return result.blob
}
}
}