@orbitdb/set-db
Version:
Set database type for orbit-db.
74 lines • 2.12 kB
JavaScript
import { Database } from "@orbitdb/core";
const type = "set";
const SetDb = () => async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate, }) => {
const database = await Database({
ipfs,
identity,
address,
name,
access,
directory,
meta,
headsStorage,
entryStorage,
indexStorage,
referencesCount,
syncAutomatically,
onUpdate,
});
const { add, del, iterator, all } = SetApi({ database });
return {
...database,
type,
add,
del,
iterator,
all,
};
};
SetDb.type = type;
export const SetApi = ({ database }) => {
const add = async (value) => {
// TODO: check if value already exists? (Optimises memory over speed)
return database.addOperation({ op: "ADD", key: null, value });
};
const del = async (value) => {
return database.addOperation({ op: "DEL", key: null, value });
};
const iterator = async function* ({ amount, } = {}) {
const vals = {};
let count = 0;
for await (const entry of database.log.traverse()) {
const { op, value } = entry.payload;
const key = JSON.stringify(value);
if (op === "ADD" && !vals[key]) {
vals[key] = true;
count++;
const hash = entry.hash;
yield { value, hash };
}
else if (op === "DEL" && !vals[key]) {
vals[key] = true;
}
if (amount !== undefined && count >= amount) {
break;
}
}
};
const all = async () => {
const values = [];
for await (const entry of iterator()) {
values.unshift(entry);
}
return new Set(values.map((v) => v.value));
};
return {
add,
del,
iterator,
all,
};
};
SetApi.type = type;
export default SetDb;
//# sourceMappingURL=set.js.map