hyperns-service
Version:
HyperNS service, based on autobase
86 lines (68 loc) • 2.17 kB
JavaScript
const IdEnc = require('hypercore-id-encoding')
const ReadyResource = require('ready-resource')
const HyperNS = require('hyperns')
class HyperNsLookupClient extends ReadyResource {
constructor (nameServiceKey, encryptionKey, swarm, store) {
super()
this.nameServiceKey = IdEnc.decode(nameServiceKey)
this.encryptionKey = IdEnc.decode(encryptionKey)
// Note: corestore replication is NOT handled here
this.swarm = swarm
this.store = store // Normally a namespace (life cycle managed here)
this.core = this.store.get({ key: this.nameServiceKey })
this.db = null
}
async _open () {
await this.core.ready()
this.core.setEncryptionKey(this.encryptionKey, { isBlockKey: true })
this.db = new HyperNS(this.core, { extension: false })
await this.db.ready()
this.swarm.join(this.core.discoveryKey, { client: true, server: false })
}
async _close () {
// Note: assumes we're not interested in this core elsewhere in our app
this.swarm.leave(this.core.discoveryKey)
await this.db.close()
await this.store.close()
}
async ensureDbLoaded (timeoutMs = 10000) {
if (this.db.db.engine.core.length > 0) return
await new Promise((resolve, reject) => {
let cancelHandler = null
let timeout = null
const cleanup = () => {
this.removeListener('close', cancelHandler)
clearTimeout(timeout)
}
timeout = setTimeout(
() => {
cleanup()
reject(new Error('Load-db Timeout'))
},
timeoutMs
)
cancelHandler = () => {
cleanup()
reject(new Error('Lookup client closed'))
}
this.on('close', cancelHandler)
this.db.db.engine.core.once('append', () => {
cleanup()
resolve()
})
})
}
async lookup (name) {
if (this.db.db.engine.core.length === 0) {
throw new Error('Database not yet loaded')
}
const record = await this.db.get(name)
if (!record) return null
return {
name: record.name,
publicKey: record.publicKey,
blindPeers: record.blindPeers
}
}
}
module.exports = HyperNsLookupClient