Skip to content

Instantly share code, notes, and snippets.

@Nuhvi
Last active August 17, 2022 08:41
Show Gist options
  • Save Nuhvi/574eec01ffbbd449f9df65329e3ac0ed to your computer and use it in GitHub Desktop.
Save Nuhvi/574eec01ffbbd449f9df65329e3ac0ed to your computer and use it in GitHub Desktop.
import Hypercore from 'hypercore';
import Hyperbee from 'hyperbee';
class Hyperstate extends Hypercore {
constructor(storage, key, opts) {
super(storage, key, opts);
this.state = {};
this.opening = this._open();
this.opening.catch(noop);
this.opened = false;
}
async _open() {
await super.ready();
if (this.length > 0) this.state = await this.get(this.length - 1);
}
async ready() {
return this.opening;
}
async put(key, value) {
const snapshot = this.snapshot({ valueEncoding: this.valueEncoding });
const payload = { [key]: value };
if (snapshot.length === 0) {
return super.append(payload);
}
const state = (await snapshot.get(snapshot.length - 1)) || {};
await snapshot.clear(0, snapshot.length);
this.state = { ...state, ...payload };
return super.append(this.state);
}
}
function noop() {}
const OVERHEAD_SIZE = 1000;
async function test(db) {
await db.put(
'overhead',
Buffer.alloc(OVERHEAD_SIZE).fill('overhead').toString(),
);
for (let i = 0; i < 100; i++) {
await db.put('foo', 'bar' + i);
}
}
const lightdb = new Hyperstate('./storage/hyperstate', {
valueEncoding: 'json',
});
await lightdb.ready();
await test(lightdb);
const bee = new Hyperbee(new Hypercore('./storage/hyperbee'), {
keyEncoding: 'utf8',
valueEncoding: 'json',
});
await test(bee);
console.log(lightdb.state.foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment