community
community copied to clipboard
Proposal: Add `db.has(key)` and `db.hasMany(keys)`
I love working with the Level stack. However, I miss one feature: a way to check any db whether it has a value for a key, without actually retrieving the value. Right now, as a workaround, I extend LevelUp
instances with has
and hasMany
keys like so (TypeScript):
db.has = async function (
key: K,
options?: AbstractOptions,
): Promise<boolean> {
try {
await this.get(key, options);
return true;
} catch (e) {
if (e.notFound) {
return false;
} else {
throw e; // rethrow other exceptions
}
}
};
// similar for hasMany using getMany mapped with `x => !(x === undefined)`
However, this is not as efficient as it could be, since the underlying storage can probably implement has
much more efficient than first actually retrieving the value, just for it to be abandoned in this workaround.
This could even be implemented in levelup
first usind above code, if levelup
itself cannot find functions has
or hasMany
on the abstract-leveldown
passed to it. This way, leveldown implementations can one by one add has
/hasMany
while levelup
can already provide the functionality in a backwards-compatible fashion.