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

Commit

Permalink
feat: improve query by a lot
Browse files Browse the repository at this point in the history
  • Loading branch information
hugomrdias committed Apr 2, 2020
1 parent 71d6804 commit 2ba5203
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
'use strict'

const { Buffer } = require('buffer')
const { openDB, deleteDB } = require('idb')
const { Key, Errors, utils } = require('interface-datastore')
const { filter, sortAll } = utils

const { openDB, deleteDB } = require('idb')

function isStrictTypedArray (arr) {
return (
arr instanceof Int8Array ||
Expand Down Expand Up @@ -35,8 +34,18 @@ function typedarrayToBuffer (arr) {
}
}

function str2ab (str) {
var buf = new ArrayBuffer(str.length)
var bufView = new Uint8Array(buf)
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i)
}
return buf
}

const queryIt = async function * (q, store, location) {
let cursor = await store.transaction(location).store.openCursor()
const range = q.prefix ? self.IDBKeyRange.bound(str2ab(q.prefix), str2ab(q.prefix + '\xFF'), false, true) : undefined
let cursor = await store.transaction(location).store.openCursor(range)
let limit = 0

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

const key = new Key(Buffer.from(cursor.key))
const value = Buffer.from(cursor.value)
if (!q.prefix || (q.prefix && key.toString().startsWith(q.prefix))) {
if (q.keysOnly) {
yield { key }
} else {
yield { key, value }
}
if (q.keysOnly) {
yield { key }
} else {
const value = Buffer.from(cursor.value)
yield { key, value }
}
cursor = await cursor.continue()
}
Expand Down Expand Up @@ -163,7 +170,6 @@ class IdbDatastore {
if (this.store === null) {
throw new Error('Datastore needs to be opened.')
}

let it = queryIt(q, this.store, this.location)

if (Array.isArray(q.filters)) {
Expand Down

0 comments on commit 2ba5203

Please sign in to comment.