Refactor heads

This commit is contained in:
haad 2025-05-09 12:37:13 +02:00
parent 1d08f996c5
commit 0295262092

View File

@ -14,16 +14,8 @@ const Heads = async ({ storage, heads, decryptPayloadFn, decryptEntryFn }) => {
const put = async (heads) => { const put = async (heads) => {
heads = findHeads(heads) heads = findHeads(heads)
for (const head of heads) { const newHeads = heads.map(e => ({ hash: e.hash, next: e.next }))
// Store the entry's hash and nexts await storage.put('heads', JSON.stringify(newHeads))
await storage.put(head.hash, head.next)
}
}
const set = async (heads) => {
// TODO: fix storage write fluctuation
await storage.clear()
await put(heads)
} }
const add = async (head) => { const add = async (head) => {
@ -32,20 +24,21 @@ const Heads = async ({ storage, heads, decryptPayloadFn, decryptEntryFn }) => {
return return
} }
const newHeads = findHeads([...currentHeads, head]) const newHeads = findHeads([...currentHeads, head])
await set(newHeads) await put(newHeads)
return newHeads return newHeads
} }
const remove = async (hash) => { const remove = async (hash) => {
const currentHeads = await all() const currentHeads = await all()
const newHeads = currentHeads.filter(e => e.hash !== hash) const newHeads = currentHeads.filter(e => e.hash !== hash)
await set(newHeads) await put(newHeads)
} }
const iterator = async function * () { const iterator = async function * () {
const it = storage.iterator() const e = await storage.get('heads')
for await (const [hash, next] of it) { const headHashes = e ? JSON.parse(e) : []
yield { hash, next } for (const hash of headHashes) {
yield hash
} }
} }
@ -66,11 +59,13 @@ const Heads = async ({ storage, heads, decryptPayloadFn, decryptEntryFn }) => {
} }
// Initialize the heads if given as parameter // Initialize the heads if given as parameter
await put(heads || []) if (heads) {
await put(heads)
}
return { return {
put, put,
set, set: put,
add, add,
remove, remove,
iterator, iterator,