/
index.ts
244 lines (198 loc) · 5.6 KB
/
index.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/**
* @packageDocumentation
*
* A Datastore implementation for browsers that stores data in [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API).
*
* @example
*
* ```js
* import { IDBDatastore } from 'datastore-idb'
*
* const store = new IDBDatastore('path/to/store')
* ```
*/
import { Errors, BaseDatastore } from 'datastore-core'
import { openDB, deleteDB, type IDBPDatabase } from 'idb'
import { type Batch, Key, type KeyQuery, type Pair, type Query } from 'interface-datastore'
import filter from 'it-filter'
import sort from 'it-sort'
export interface IDBDatastoreInit {
/**
* A prefix to use for all database keys (default: '')
*/
prefix?: string
/**
* The database version (default: 1)
*/
version?: number
}
export class IDBDatastore extends BaseDatastore {
private readonly location: string
private readonly version: number
private db?: IDBPDatabase
constructor (location: string, init: IDBDatastoreInit = {}) {
super()
this.location = `${init.prefix ?? ''}${location}`
this.version = init.version ?? 1
}
async open (): Promise<void> {
try {
const location = this.location
this.db = await openDB(location, this.version, {
upgrade (db) {
db.createObjectStore(location)
}
})
} catch (err: any) {
throw Errors.dbOpenFailedError(err)
}
}
async close (): Promise<void> {
this.db?.close()
}
async put (key: Key, val: Uint8Array): Promise<Key> {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
try {
await this.db.put(this.location, val, key.toString())
return key
} catch (err: any) {
throw Errors.dbWriteFailedError(err)
}
}
async get (key: Key): Promise<Uint8Array> {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
let val: Uint8Array | undefined
try {
val = await this.db.get(this.location, key.toString())
} catch (err: any) {
throw Errors.dbReadFailedError(err)
}
if (val === undefined) {
throw Errors.notFoundError()
}
return val
}
async has (key: Key): Promise<boolean> {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
try {
return Boolean(await this.db.getKey(this.location, key.toString()))
} catch (err: any) {
throw Errors.dbReadFailedError(err)
}
}
async delete (key: Key): Promise<void> {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
try {
await this.db.delete(this.location, key.toString())
} catch (err: any) {
throw Errors.dbWriteFailedError(err)
}
}
batch (): Batch {
const puts: Pair[] = []
const dels: Key[] = []
return {
put (key, value) {
puts.push({ key, value })
},
delete (key) {
dels.push(key)
},
commit: async () => {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
const tx = this.db.transaction(this.location, 'readwrite')
try {
const ops = puts.filter(({ key }) => {
// don't put a key we are about to delete
return dels.find(delKey => delKey.toString() === key.toString()) == null
})
.map(put => {
return async () => {
await tx.store.put(put.value, put.key.toString())
}
})
.concat(dels.map(key => {
return async () => {
await tx.store.delete(key.toString())
}
}))
.concat(async () => {
await tx.done
})
await Promise.all(ops.map(async op => { await op() }))
} catch {
tx.abort()
}
}
}
}
async * query (q: Query): AsyncIterable<Pair> {
let it = this.#queryIt(q, (key, value) => {
return { key, value }
})
if (Array.isArray(q.filters)) {
it = q.filters.reduce((it, f) => filter(it, f), it)
}
if (Array.isArray(q.orders)) {
it = q.orders.reduce((it, f) => sort(it, f), it)
}
yield * it
}
async * queryKeys (q: KeyQuery): AsyncIterable<Key> {
let it = this.#queryIt(q, (key) => key)
if (Array.isArray(q.filters)) {
it = q.filters.reduce((it, f) => filter(it, f), it)
}
if (Array.isArray(q.orders)) {
it = q.orders.reduce((it, f) => sort(it, f), it)
}
yield * it
}
async * #queryIt <T> (q: { prefix?: string, offset?: number, limit?: number }, transform: (key: Key, value: Uint8Array) => T): AsyncIterable<T> {
if (this.db == null) {
throw new Error('Datastore needs to be opened.')
}
let yielded = 0
let index = -1
for (const key of await this.db.getAllKeys(this.location)) {
if (q.prefix != null && !key.toString().startsWith(q.prefix)) { // eslint-disable-line @typescript-eslint/no-base-to-string
continue
}
if (q.limit != null && yielded === q.limit) {
return
}
index++
if (q.offset != null && index < q.offset) {
continue
}
const k = new Key(key.toString()) // eslint-disable-line @typescript-eslint/no-base-to-string
let value: Uint8Array | undefined
try {
value = await this.get(k)
} catch (err: any) {
if (err.code !== 'ERR_NOT_FOUND') {
throw err
}
continue
}
if (value == null) {
continue
}
yield transform(k, value)
yielded++
}
}
async destroy (): Promise<void> {
await deleteDB(this.location)
}
}