Skip to content
This repository was archived by the owner on Dec 2, 2024. It is now read-only.

Commit da9fc40

Browse files
committed
Drop support of key & value types other than string and Buffer
1 parent 69645a4 commit da9fc40

16 files changed

+179
-812
lines changed

README.md

Lines changed: 9 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# level-js
22

3-
> An [`abstract-leveldown`][abstract-leveldown] compliant store on top of [IndexedDB][indexeddb], which is in turn implemented on top of [LevelDB][leveldb] which brings this whole shebang full circle.
3+
> An [`abstract-leveldown`][abstract-leveldown] compliant store on top of [IndexedDB][indexeddb].
44
55
[![level badge][level-badge]][awesome]
66
[![npm](https://img.shields.io/npm/v/level-js.svg?label=&logo=npm)](https://www.npmjs.com/package/level-js)
@@ -35,13 +35,11 @@ Here are the goals of `level-js`:
3535

3636
- Store large amounts of data in modern browsers
3737
- Pass the full [`abstract-leveldown`][abstract-leveldown] test suite
38-
- Support [`Buffer`][buffer] keys and values
39-
- Support all key types of IndexedDB Second Edition
40-
- Support all value types of the [structured clone algorithm][structured-clone-algorithm] except for `null` and `undefined`
38+
- Support string and binary keys and values
4139
- Be as fast as possible
42-
- Sync with [multilevel](https://github.com/juliangruber/multilevel) over ASCII or binary transports.
40+
- ~~Sync with [multilevel](https://github.com/juliangruber/multilevel) over ASCII or binary transports.~~
4341

44-
Being `abstract-leveldown` compliant means you can use many of the [Level modules][awesome] on top of this library. For some demos of it working, see [**@brycebaril**](https://github.com/brycebaril)'s presentation [Path of the NodeBases Jedi](http://brycebaril.github.io/nodebase_jedi/#/vanilla).
42+
Being `abstract-leveldown` compliant means you can use many of the [Level modules][awesome] on top of this library.
4543

4644
## Example
4745

@@ -80,120 +78,17 @@ const value = await db.get('hello')
8078

8179
## Type Support
8280

83-
Unlike [`leveldown`][leveldown], `level-js` does not stringify keys or values. This means that in addition to strings and Buffers you can store almost any JavaScript type without the need for [`encoding-down`][encoding-down].
81+
Keys and values can be a string or binary. Supported binary types include [`Buffer`][buffer], `ArrayBuffer` or a view thereof (typed arrays). Any other type will be irreversibly stringified. The only exceptions are `null` and `undefined`. Keys and values of that type are rejected.
8482

85-
### Values
83+
In order to sort string and binary keys the same way, for compatibility with `leveldown` and the larger ecosystem, `level-js` internally converts keys and values to binary before passing them to IndexedDB. If binary keys are not supported by the environment (like IE11) `level-js` falls back to `String(key)`.
8684

87-
All value types of the [structured clone algorithm][structured-clone-algorithm] are supported except for `null` and `undefined`. Depending on the environment, this includes:
85+
If you desire non-destructive encoding (e.g. to store and retrieve numbers as-is), wrap `level-js` with [`encoding-down`][encoding-down]. Alternatively install [`level`][level] which conveniently bundles [`levelup`][levelup], `level-js` and `encoding-down`. Such an approach is also recommended if you want to achieve universal (isomorphic) behavior. For example, you could have [`leveldown`][leveldown] in a backend and `level-js` in the frontend. The `level` package does exactly that.
8886

89-
- Number, including `NaN`, `Infinity` and `-Infinity`
90-
- String, Boolean, Date, RegExp, Array, Object
91-
- ArrayBuffer or a view thereof (typed arrays);
92-
- Map, Set, Blob, File, FileList, ImageData (limited support).
93-
94-
In addition `level-js` stores [`Buffer`][buffer] values without transformation. This works in all target environments because `Buffer` is a subclass of `Uint8Array`, meaning such values can be passed to `IndexedDB` as-is.
95-
96-
When getting or iterating binary values, regardless of whether they were stored as a `Buffer`, `ArrayBuffer` or a view thereof, values will return as a `Buffer`. This behavior can be disabled, in which case `ArrayBuffer` returns as `ArrayBuffer`, typed arrays return as typed arrays and `Buffer` returns as `Uint8Array`:
87+
When getting or iterating keys and values, regardless of the type with which they were stored, keys and values will return as a Buffer unless the `asBuffer`, `keyAsBuffer` or `valueAsBuffer` options are set, in which case strings are returned. Setting these options is not needed when `level-js` is wrapped with `encoding-down`, which determines the optimal return type by the chosen encoding.
9788

9889
```js
9990
db.get('key', { asBuffer: false })
100-
db.iterator({ valueAsBuffer: false })
101-
```
102-
103-
If the environment does not support a type, it will throw an error which `level-js` catches and passes to the callbacks of `put` or `batch`. For example, IE does not support typed array values. At the time of writing, Chrome is the only browser that supports all types listed above.
104-
105-
### Keys
106-
107-
All key types of IndexedDB Second Edition are supported. Depending on the environment, this includes:
108-
109-
- Number, including `Infinity` and `-Infinity`, but not `NaN`
110-
- Date, except invalid (`NaN`)
111-
- String
112-
- ArrayBuffer or a view thereof (typed arrays);
113-
- Array, except cyclical, empty and sparse arrays. Elements must be valid types themselves.
114-
115-
In addition you can use [`Buffer`][buffer] keys, giving `level-js` the same power as implementations like `leveldown` and `memdown`. When iterating binary keys, regardless of whether they were stored as `Buffer`, `ArrayBuffer` or a view thereof, keys will return as a `Buffer`. This behavior can be disabled, in which case binary keys will always return as `ArrayBuffer`:
116-
117-
```js
118-
db.iterator({ keyAsBuffer: false })
119-
```
120-
121-
Note that this behavior is slightly different from values due to the way that IndexedDB works. IndexedDB stores binary _values_ using the structured clone algorithm, which preserves views, but it stores binary _keys_ as an array of octets, so that it is able to compare and sort differently typed keys.
122-
123-
If the environment does not support a type, it will throw an error which `level-js` catches and passes to the callbacks of `get`, `put`, `del`, `batch` or an iterator. Exceptions are:
124-
125-
- `null` and `undefined`: rejected early by `abstract-leveldown`
126-
- Binary and array keys: if not supported by the environment, `level-js` falls back to `String(key)`.
127-
128-
### Normalization
129-
130-
If you desire normalization for keys and values (e.g. to stringify numbers), wrap `level-js` with [`encoding-down`][encoding-down]. Alternatively install [`level`][level] which conveniently bundles [`levelup`][levelup], `level-js` and `encoding-down`. Such an approach is also recommended if you want to achieve universal (isomorphic) behavior or to smooth over type differences between browsers. For example, you could have [`leveldown`][leveldown] in a backend and `level-js` in the frontend. The `level` package does exactly that.
131-
132-
Another reason you might want to use `encoding-down` is that the structured clone algorithm, while rich in types, can be slower than `JSON.stringify`.
133-
134-
### Sort Order
135-
136-
Unless `level-js` is wrapped with [`encoding-down`][encoding-down], IndexedDB will sort your keys in the following order:
137-
138-
1. number (numeric)
139-
2. date (numeric, by epoch offset)
140-
3. binary (bitwise)
141-
4. string (lexicographic)
142-
5. array (componentwise).
143-
144-
You can take advantage of this fact with `levelup` streams. For example, if your keys are dates, you can select everything greater than a specific date (let's be happy and ignore timezones for a moment):
145-
146-
```js
147-
const db = levelup(leveljs('time-db'))
148-
149-
db.createReadStream({ gt: new Date('2019-01-01') })
150-
.pipe(..)
151-
```
152-
153-
Or if your keys are arrays, you can do things like:
154-
155-
```js
156-
const db = levelup(leveljs('books-db'))
157-
158-
await db.put(['Roald Dahl', 'Charlie and the Chocolate Factory'], {})
159-
await db.put(['Roald Dahl', 'Fantastic Mr Fox'], {})
160-
161-
// Select all books by Roald Dahl
162-
db.createReadStream({ gt: ['Roald Dahl'], lt: ['Roald Dahl', '\xff'] })
163-
.pipe(..)
164-
```
165-
166-
To achieve this on other `abstract-leveldown` implementations, wrap them with [`encoding-down`][encoding-down] and [`charwise`][charwise] (or similar).
167-
168-
#### Known Browser Issues
169-
170-
IE11 and Edge yield incorrect results for `{ gte: '' }` if the database contains any key types other than strings.
171-
172-
### Buffer vs ArrayBuffer
173-
174-
For interoperability it is recommended to use `Buffer` as your binary type. While we recognize that Node.js core modules are moving towards supporting `ArrayBuffer` and views thereof, `Buffer` remains the primary binary type in the Level ecosystem.
175-
176-
That said: if you want to `put()` an `ArrayBuffer` you can! Just know that it will come back as a `Buffer` by default. If you want to `get()` or iterate stored `ArrayBuffer` data as an `ArrayBuffer`, you have a few options. Without `encoding-down`:
177-
178-
```js
179-
const db = levelup(leveljs('mydb'))
180-
181-
// Yields an ArrayBuffer, Buffer and ArrayBuffer
182-
const value1 = await db.get('key', { asBuffer: false })
183-
const value2 = await db.get('key')
184-
const value3 = value2.buffer
185-
```
186-
187-
With `encoding-down` (or `level`) you can use the `id` encoding to selectively bypass encodings:
188-
189-
```js
190-
const encode = require('encoding-down')
191-
const db = levelup(encode(leveljs('mydb'), { valueEncoding: 'binary' }))
192-
193-
// Yields an ArrayBuffer, Buffer and ArrayBuffer
194-
const value1 = await db.get('key', { valueEncoding: 'id' })
195-
const value2 = await db.get('key')
196-
const value3 = value2.buffer
91+
db.iterator({ keyAsBuffer: false, valueAsBuffer: false })
19792
```
19893

19994
## Install
@@ -268,22 +163,16 @@ To sustain [`Level`](https://github.com/Level) and its activities, become a back
268163

269164
[indexeddb]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
270165

271-
[leveldb]: https://github.com/google/leveldb
272-
273166
[buffer]: https://nodejs.org/api/buffer.html
274167

275168
[awesome]: https://github.com/Level/awesome
276169

277170
[abstract-leveldown]: https://github.com/Level/abstract-leveldown
278171

279-
[charwise]: https://github.com/dominictarr/charwise
280-
281172
[levelup]: https://github.com/Level/levelup
282173

283174
[leveldown]: https://github.com/Level/leveldown
284175

285176
[level]: https://github.com/Level/level
286177

287178
[encoding-down]: https://github.com/Level/encoding-down
288-
289-
[structured-clone-algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm

index.js

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ module.exports = Level
77
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
88
var inherits = require('inherits')
99
var Iterator = require('./iterator')
10-
var mixedToBuffer = require('./util/mixed-to-buffer')
10+
var serialize = require('./util/serialize')
11+
var deserialize = require('./util/deserialize')
1112
var setImmediate = require('./util/immediate')
1213
var support = require('./util/support')
1314

@@ -25,13 +26,31 @@ function Level (location, opts) {
2526
this.location = location
2627
this.prefix = opts.prefix || DEFAULT_PREFIX
2728
this.version = parseInt(opts.version || 1, 10)
29+
30+
// Experimental, do not externally rely on this object yet.
31+
// See Level/community#42.
32+
this.supports = {
33+
bufferKeys: Level.binaryKeys,
34+
binaryKeys: Level.binaryKeys,
35+
keys: {
36+
string: true,
37+
buffer: Level.binaryKeys,
38+
arrayBuffer: Level.binaryKeys,
39+
typedArray: Level.binaryKeys
40+
},
41+
permanence: true,
42+
snapshots: true, // For now (#86)
43+
seek: false, // #178
44+
clear: false, // #175
45+
createIfMissing: false,
46+
errorIfExists: false
47+
}
2848
}
2949

3050
inherits(Level, AbstractLevelDOWN)
3151

32-
// Detect binary and array key support (IndexedDB Second Edition)
52+
// Detect binary key support (IndexedDB Second Edition)
3353
Level.binaryKeys = support.binaryKeys(indexedDB)
34-
Level.arrayKeys = support.arrayKeys(indexedDB)
3554

3655
Level.prototype._open = function (options, callback) {
3756
var req = indexedDB.open(this.prefix + this.location, this.version)
@@ -93,11 +112,7 @@ Level.prototype._get = function (key, options, callback) {
93112
return callback(new Error('NotFound'))
94113
}
95114

96-
if (options.asBuffer) {
97-
value = mixedToBuffer(value)
98-
}
99-
100-
callback(null, value)
115+
callback(null, deserialize(value, options.asBuffer))
101116
})
102117
}
103118

@@ -131,27 +146,12 @@ Level.prototype._put = function (key, value, options, callback) {
131146
this.await(req, callback)
132147
}
133148

134-
// Valid key types in IndexedDB Second Edition:
135-
//
136-
// - Number, except NaN. Includes Infinity and -Infinity
137-
// - Date, except invalid (NaN)
138-
// - String
139-
// - ArrayBuffer or a view thereof (typed arrays). In level-js we also support
140-
// Buffer (which is an Uint8Array) (and the primary binary type of Level).
141-
// - Array, except cyclical and empty (e.g. Array(10)). Elements must be valid
142-
// types themselves.
143149
Level.prototype._serializeKey = function (key) {
144-
if (Buffer.isBuffer(key)) {
145-
return Level.binaryKeys ? key : key.toString()
146-
} else if (Array.isArray(key)) {
147-
return Level.arrayKeys ? key.map(this._serializeKey, this) : String(key)
148-
} else {
149-
return key
150-
}
150+
return serialize(key, this.supports.binaryKeys)
151151
}
152152

153153
Level.prototype._serializeValue = function (value) {
154-
return value
154+
return serialize(value, true)
155155
}
156156

157157
Level.prototype._iterator = function (options) {

iterator.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
var inherits = require('inherits')
66
var AbstractIterator = require('abstract-leveldown').AbstractIterator
77
var ltgt = require('ltgt')
8-
var mixedToBuffer = require('./util/mixed-to-buffer')
8+
var deserialize = require('./util/deserialize')
99
var setImmediate = require('./util/immediate')
1010
var noop = function () {}
1111

@@ -23,6 +23,8 @@ function Iterator (db, location, options) {
2323
this._error = null
2424
this._transaction = null
2525

26+
this._keys = options.keys
27+
this._values = options.values
2628
this._keyAsBuffer = options.keyAsBuffer
2729
this._valueAsBuffer = options.valueAsBuffer
2830

@@ -126,8 +128,17 @@ Iterator.prototype._next = function (callback) {
126128
var key = this._cache.shift()
127129
var value = this._cache.shift()
128130

129-
if (this._keyAsBuffer) key = mixedToBuffer(key)
130-
if (this._valueAsBuffer) value = mixedToBuffer(value)
131+
if (this._keys && key !== undefined) {
132+
key = deserialize(key, this._keyAsBuffer)
133+
} else {
134+
key = undefined
135+
}
136+
137+
if (this._values && value !== undefined) {
138+
value = deserialize(value, this._valueAsBuffer)
139+
} else {
140+
value = undefined
141+
}
131142

132143
setImmediate(function () {
133144
callback(null, key, value)

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
"abstract-leveldown": "~6.0.1",
3030
"immediate": "~3.2.3",
3131
"inherits": "^2.0.3",
32-
"ltgt": "^2.1.2",
33-
"typedarray-to-buffer": "~3.1.5"
32+
"ltgt": "^2.1.2"
3433
},
3534
"devDependencies": {
3635
"airtap": "^2.0.0",

0 commit comments

Comments
 (0)