Level / abstract-level

Abstract class for a lexicographically sorted key-value database.
MIT License
128 stars 8 forks source link

Add an option to return undefined when key is not found rather than throwing an error LEVEL_NOT_FOUND #87

Closed mckravchyk closed 5 months ago

mckravchyk commented 5 months ago

A key not being found is a valid scenario, i.e. sometimes you just want to default to some values if they are not set, using a try catch for this is quite cumbersome. Would you consider adding an extra option to the constructor that would make .get() return undefined rather than throwing?

undefined is not a JSON value so it would be a pretty clear marker that the key is not set.

As for the types, it's possible to modify the return type on get by making constructor options part of class generic. So the return type of .get() would be like Options extends { allowUndefined: true } ? Promise<V | undefined> : Promise<V>

I am using getMany with destructuring as a workaround, i.e.

const [value] = await db.getMany(['key']);
vweevers commented 5 months ago

Done in https://github.com/Level/abstract-level/pull/49. Hasn't been released downstream yet (e.g. in level).