blockstore-core
Version:
Contains various implementations of the API contract described in interface-blockstore
70 lines • 2.16 kB
JavaScript
import { NotFoundError } from 'interface-store';
import all from 'it-all';
import { base32 } from 'multiformats/bases/base32';
import { CID } from 'multiformats/cid';
import * as raw from 'multiformats/codecs/raw';
import * as Digest from 'multiformats/hashes/digest';
import { BaseBlockstore } from "./base.js";
function isPromise(p) {
return typeof p?.then === 'function';
}
export class MemoryBlockstore extends BaseBlockstore {
data;
constructor() {
super();
this.data = new Map();
}
put(key, val, options) {
options?.signal?.throwIfAborted();
let buf;
if (val instanceof Uint8Array) {
buf = [val];
}
else {
const result = all(val);
if (isPromise(result)) {
return result.then(val => {
return this._put(key, val, options);
});
}
else {
buf = result;
}
}
return this._put(key, buf, options);
}
_put(key, val, options) {
options?.signal?.throwIfAborted();
this.data.set(base32.encode(key.multihash.bytes), val);
return key;
}
*get(key, options) {
options?.signal?.throwIfAborted();
const buf = this.data.get(base32.encode(key.multihash.bytes));
if (buf == null) {
throw new NotFoundError();
}
yield* buf;
}
has(key, options) {
options?.signal?.throwIfAborted();
return this.data.has(base32.encode(key.multihash.bytes));
}
async delete(key, options) {
options?.signal?.throwIfAborted();
this.data.delete(base32.encode(key.multihash.bytes));
}
*getAll(options) {
options?.signal?.throwIfAborted();
for (const [key, value] of this.data.entries()) {
yield {
cid: CID.createV1(raw.code, Digest.decode(base32.decode(key))),
bytes: (async function* () {
yield* value;
})()
};
options?.signal?.throwIfAborted();
}
}
}
//# sourceMappingURL=memory.js.map