forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindexed-storage.ts
More file actions
210 lines (176 loc) · 7.34 KB
/
indexed-storage.ts
File metadata and controls
210 lines (176 loc) · 7.34 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const ALL_TABLES = ['stat', 'timeline'] as const
export type Table = typeof ALL_TABLES[number]
export type Key<T = Record<string, number>> = keyof T & string
type IndexConfig<T = Record<string, unknown>> = {
key: Key<T> | Key<T>[]
unique?: boolean
}
export type Index<T = Record<string, unknown>> = Key<T> | Key<T>[] | IndexConfig<T>
function normalizeIndex<T = Record<string, number>>(index: Index<T>): IndexConfig<T> {
return typeof index === 'string' || Array.isArray(index) ? { key: index } : index
}
function formatIdxName<T = Record<string, number>>(key: IndexConfig<T>['key']): string {
const keyStr = Array.isArray(key) ? [...key].sort().join('_') : key
return `idx_${keyStr}`
}
export function req2Promise<T = unknown>(req: IDBRequest<T>): Promise<T | undefined> {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result)
req.onerror = (ev) => {
console.error("Failed to request indexed-db", ev, req.error)
reject(req.error)
}
})
}
export async function iterateCursor<T = unknown>(
req: IDBRequest<IDBCursorWithValue | null>
): Promise<readonly T[]>
export async function iterateCursor<T = unknown>(
req: IDBRequest<IDBCursorWithValue | null>,
processor: (cursor: IDBCursorWithValue) => void | Promise<void>
): Promise<void>
export async function iterateCursor<T = unknown>(
req: IDBRequest<IDBCursorWithValue | null>,
processor?: (cursor: IDBCursorWithValue) => void | Promise<void>
): Promise<readonly T[] | void> {
const collectResults = !processor
const results: T[] = []
return new Promise((resolve, reject) => {
req.onsuccess = async () => {
const cursor = req.result
if (!cursor) return resolve(collectResults ? results : undefined)
try {
collectResults && results.push(cursor.value as T)
await processor?.(cursor)
cursor.continue()
} catch (error) {
reject(error)
}
}
req.onerror = () => reject(req.error)
})
}
export function closedRangeKey(lower: IDBValidKey | undefined, upper: IDBValidKey | undefined): IDBKeyRange | undefined {
if (lower !== undefined && upper !== undefined) {
if (lower > upper) {
[lower, upper] = [upper, lower]
}
return IDBKeyRange.bound(lower, upper, false, false)
} else if (lower !== undefined) {
return IDBKeyRange.lowerBound(lower, false)
} else if (upper !== undefined) {
return IDBKeyRange.upperBound(upper, false)
} else {
return undefined
}
}
export type IndexResult<FilterCoverage> = {
cursorReq: IDBRequest<IDBCursorWithValue | null>
coverage?: FilterCoverage
}
export abstract class BaseIDBStorage<T = Record<string, unknown>> {
private DB_NAME = `tt4b_${chrome.runtime.id}` as const
private db: IDBDatabase | undefined
abstract indexes: Index<T>[]
abstract key: Key<T> | Key<T>[]
abstract table: Table
protected async initDb(): Promise<IDBDatabase> {
if (this.db) return this.db
const factory = typeof window !== 'undefined' ? window.indexedDB : globalThis.indexedDB
const checkRequest = factory.open(this.DB_NAME)
return new Promise((resolve, reject) => {
checkRequest.onsuccess = () => {
const db = checkRequest.result
const storeExisted = db.objectStoreNames.contains(this.table)
const needUpgrade = !storeExisted || this.needUpgradeIndexes(db)
if (!needUpgrade) {
this.db = db
return resolve(db)
}
const currentVersion = db.version
db.close()
const upgradeRequest = factory.open(this.DB_NAME, currentVersion + 1)
upgradeRequest.onupgradeneeded = () => {
const upgradeDb = upgradeRequest.result
const transaction = upgradeRequest.transaction
if (!transaction) return reject("Failed to get transaction of upgrading request")
let store = upgradeDb.objectStoreNames.contains(this.table)
? transaction.objectStore(this.table)
: upgradeDb.createObjectStore(this.table, { keyPath: this.key })
this.createIndexes(store)
}
upgradeRequest.onsuccess = () => {
console.log("IndexedDB upgraded")
this.db = upgradeRequest.result
resolve(upgradeRequest.result)
}
upgradeRequest.onerror = () => reject(upgradeRequest.error)
}
checkRequest.onerror = () => reject(checkRequest.error)
})
}
private needUpgradeIndexes(db: IDBDatabase): boolean {
try {
const transaction = db.transaction(this.table, 'readonly')
const store = transaction.objectStore(this.table)
const indexNames = store.indexNames
for (const index of this.indexes) {
const { key } = normalizeIndex(index)
const idxName = formatIdxName(key)
if (!indexNames.contains(idxName)) {
return true
}
}
return false
} catch (e) {
console.error("Failed to check indexes", e)
return true
}
}
private createIndexes(store: IDBObjectStore) {
const existingIndexes = store.indexNames
for (const index of this.indexes) {
const { key, unique } = normalizeIndex(index)
const idxName = formatIdxName(key)
if (!existingIndexes.contains(idxName)) {
store.createIndex(idxName, key, { unique })
}
}
}
protected async withStore<T = unknown>(operation: (store: IDBObjectStore) => T | Promise<T>, mode?: IDBTransactionMode): Promise<T> {
const db = await this.initDb()
const trans = db.transaction(this.table, mode ?? 'readwrite')
try {
const store = trans.objectStore(this.table)
const result = await operation(store)
// Waiting for transaction completed
await new Promise<void>((resolve, reject) => {
trans.oncomplete = () => resolve()
trans.onerror = () => reject(trans.error)
trans.onabort = () => reject(new Error('Transaction aborted'))
})
return result
} catch (e) {
console.error("Failed to process with transaction", e)
if (!trans.error && trans.mode !== 'readonly') {
try {
trans.abort()
} catch (ignored) { }
}
throw e
}
}
protected assertIndex(store: IDBObjectStore, key: Key<T> | Key<T>[]): IDBIndex {
const idxName = formatIdxName(key)
try {
return store.index(idxName)
} catch (err) {
console.error(`Failed to query index: table=${this.table}`, err)
throw err
}
}
protected assertIndexCursor(store: IDBObjectStore, key: Key<T> | Key<T>[], range: IDBKeyRange): IDBRequest<IDBCursorWithValue | null> {
const index = this.assertIndex(store, key)
return index.openCursor(range)
}
}