Skip to content

Commit

Permalink
Add db.getMany(keys)
Browse files Browse the repository at this point in the history
  • Loading branch information
vweevers committed Sep 25, 2021
1 parent 18e1fd1 commit 5318588
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 1 deletion.
26 changes: 26 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ DB.prototype._get = function (key, opts, cb) {
})
}

DB.prototype._getMany = function (keys, opts, cb) {
keys = keys.map((key) => this.codec.encodeKey(key, opts))
opts.asBuffer = this.codec.valueAsBuffer(opts)

this.db.getMany(keys, opts, (err, values) => {
if (err) return cb(err)

const decoded = new Array(values.length)

for (let i = 0; i < values.length; i++) {
if (values[i] === undefined) {
decoded[i] = undefined
continue
}

try {
decoded[i] = this.codec.decodeValue(values[i], opts)
} catch (err) {
return cb(new EncodingError(err))
}
}

cb(null, decoded)
})
}

DB.prototype._del = function (key, opts, cb) {
key = this.codec.encodeKey(key, opts)
this.db.del(key, opts, cb)
Expand Down
61 changes: 60 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const testCommon = suite.common({
errorIfExists: false,

// Opt-in to new tests
clear: true
clear: true,
getMany: true
})

// Test abstract-leveldown compliance
Expand Down Expand Up @@ -197,6 +198,64 @@ test('get() forwards error from underlying store', function (t) {
})
})

test('getMany() skips decoding not-found values', function (t) {
t.plan(6)

const valueEncoding = {
encode: JSON.stringify,
decode (value) {
t.is(value, JSON.stringify(data))
return JSON.parse(value)
},
buffer: false,
type: 'test'
}

const data = { beep: 'boop' }
const db = encdown(memdown(), { valueEncoding })

db.open(function (err) {
t.error(err, 'no open() error')

db.put('foo', data, function (err) {
t.error(err, 'no put() error')

db.getMany(['foo', 'bar'], function (err, values) {
t.error(err, 'no getMany() error')
t.same(values, [data, undefined])

db.close(t.error.bind(t))
})
})
})
})

test('getMany() forwards decode error', function (t) {
const valueEncoding = {
encode: (v) => v,
decode: (v) => { throw new Error('decode error') },
buffer: false,
type: 'test'
}

const db = encdown(memdown(), { valueEncoding })

db.open(function (err) {
t.error(err, 'no open() error')

db.put('foo', 'bar', function (err) {
t.error(err, 'no put() error')

db.getMany(['foo'], function (err, values) {
t.is(err && err.message, 'decode error')
t.is(values, undefined)

db.close(t.end.bind(t))
})
})
})
})

test('_del() encodes key', function (t) {
t.plan(1)

Expand Down

0 comments on commit 5318588

Please sign in to comment.