forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfocus-record-database.ts
More file actions
63 lines (53 loc) · 2.42 KB
/
Copy pathfocus-record-database.ts
File metadata and controls
63 lines (53 loc) · 2.42 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
import {
BaseIDBStorage, closedRangeKey, iterateCursor, req2Promise, type Index, type Key, type Table,
} from './common/indexed-storage'
type Condition = {
state?: Arrayable<tt4b.focus.State>
start?: number
end?: number
}
class FocusRecordDatabase extends BaseIDBStorage<tt4b.focus.Record> {
indexes: Index<tt4b.focus.Record>[] = ['end', 'state']
key: Key<tt4b.focus.Record> = 'start'
table: Table = 'focus_record'
async add(record: tt4b.focus.Record): Promise<void> {
return this.withStore(async store => {
const req = store.add(record)
await req2Promise<IDBValidKey>(req)
})
}
async save(record: tt4b.focus.Record): Promise<void> {
return this.withStore(async store => void store.put(record))
}
async list(condition?: Condition): Promise<tt4b.focus.Record[]> {
return this.withStore(async store => {
const { state, start, end } = condition ?? {}
const states = state ? (Array.isArray(state) ? state : [state]) : undefined
// If only state filter, use state index
if (states && !start && !end) {
const index = this.assertIndex(store, 'state')
if (states.length === 1) {
const req = index.openCursor(IDBKeyRange.only(states[0]))
return await iterateCursor<tt4b.focus.Record>(req) as tt4b.focus.Record[]
}
// Multiple states: iterate all and filter
const req = index.openCursor()
const rows = await iterateCursor<tt4b.focus.Record>(req) as tt4b.focus.Record[]
return rows.filter(row => states.includes(row.state))
}
// If time range filter, use start index
if (start || end) {
const range = closedRangeKey(start, end)
const index = this.assertIndex(store, 'start')
const req = index.openCursor(range)
const rows = await iterateCursor<tt4b.focus.Record>(req) as tt4b.focus.Record[]
return states ? rows.filter(row => states.includes(row.state)) : rows
}
// No condition, return all
const req = store.openCursor()
return await iterateCursor<tt4b.focus.Record>(req) as tt4b.focus.Record[]
}, 'readonly')
}
}
const focusRecordDatabase = new FocusRecordDatabase()
export default focusRecordDatabase