Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.

Commit 2ba5203

Browse files
committed
feat: improve query by a lot
1 parent 71d6804 commit 2ba5203

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

src/index.js

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
'use strict'
22

33
const { Buffer } = require('buffer')
4+
const { openDB, deleteDB } = require('idb')
45
const { Key, Errors, utils } = require('interface-datastore')
56
const { filter, sortAll } = utils
67

7-
const { openDB, deleteDB } = require('idb')
8-
98
function isStrictTypedArray (arr) {
109
return (
1110
arr instanceof Int8Array ||
@@ -35,8 +34,18 @@ function typedarrayToBuffer (arr) {
3534
}
3635
}
3736

37+
function str2ab (str) {
38+
var buf = new ArrayBuffer(str.length)
39+
var bufView = new Uint8Array(buf)
40+
for (var i = 0, strLen = str.length; i < strLen; i++) {
41+
bufView[i] = str.charCodeAt(i)
42+
}
43+
return buf
44+
}
45+
3846
const queryIt = async function * (q, store, location) {
39-
let cursor = await store.transaction(location).store.openCursor()
47+
const range = q.prefix ? self.IDBKeyRange.bound(str2ab(q.prefix), str2ab(q.prefix + '\xFF'), false, true) : undefined
48+
let cursor = await store.transaction(location).store.openCursor(range)
4049
let limit = 0
4150

4251
if (cursor && q.offset && q.offset > 0) {
@@ -51,13 +60,11 @@ const queryIt = async function * (q, store, location) {
5160
limit++
5261

5362
const key = new Key(Buffer.from(cursor.key))
54-
const value = Buffer.from(cursor.value)
55-
if (!q.prefix || (q.prefix && key.toString().startsWith(q.prefix))) {
56-
if (q.keysOnly) {
57-
yield { key }
58-
} else {
59-
yield { key, value }
60-
}
63+
if (q.keysOnly) {
64+
yield { key }
65+
} else {
66+
const value = Buffer.from(cursor.value)
67+
yield { key, value }
6168
}
6269
cursor = await cursor.continue()
6370
}
@@ -163,7 +170,6 @@ class IdbDatastore {
163170
if (this.store === null) {
164171
throw new Error('Datastore needs to be opened.')
165172
}
166-
167173
let it = queryIt(q, this.store, this.location)
168174

169175
if (Array.isArray(q.filters)) {

0 commit comments

Comments
 (0)