Skip to content

Commit

Permalink
Add support for a close method for views (holepunchto#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewosh authored and mafintosh committed Feb 14, 2024
1 parent dbafb28 commit 861e806
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ module.exports = class Autobase extends ReadyResource {

this._hasApply = !!this._handlers.apply
this._hasOpen = !!this._handlers.open
this._hasClose = !!this._handlers.close

this._viewStore = new LinearizedStore(this)

Expand Down Expand Up @@ -259,6 +260,7 @@ module.exports = class Autobase extends ReadyResource {
}

async _close () {
if (this._hasClose) await this._handlers.close(this.view)
await this.store.close()
}

Expand Down
29 changes: 29 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,35 @@ test('basic - view', async t => {
t.alike(await base.view.get(0), block)
})

test('basic - view with close', async t => {
const [base] = await create(1, apply, open, close)

const block = { message: 'hello, world!' }
await base.append(block)

t.is(base.system.digest.writers.length, 1)
t.is(base.view.core.indexedLength, 1)
t.alike(await base.view.core.get(0), block)

t.is(base.view.lastBlock, null)
await base.close()
t.is(base.view.lastBlock.message, 'hello, world!')

function open (store) {
const core = store.get('test', { valueEncoding: 'json' })
return {
core,
lastBlock: null,
append: v => core.append(v)
}
}

async function close (view) {
view.lastBlock = await view.core.get(view.core.length - 1)
await view.core.close()
}
})

test('basic - compare views', async t => {
const bases = await create(2, apply, store => store.get('test', { valueEncoding: 'json' }))

Expand Down
4 changes: 2 additions & 2 deletions test/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ module.exports = {
compare
}

async function create (n, apply, open) {
const opts = { apply, open, valueEncoding: 'json' }
async function create (n, apply, open, close) {
const opts = { apply, open, close, valueEncoding: 'json' }
const bases = [new Autobase(new Corestore(ram, { primaryKey: Buffer.alloc(32).fill(0) }), null, opts)]
await bases[0].ready()
if (n === 1) return bases
Expand Down

0 comments on commit 861e806

Please sign in to comment.