OverviewFilesCommitsIssuesDocsReleasesPeers

mirall-cli / node_modules / hyperdht / lib / plugin.js

66 lines · javascript ref:
const c = require('compact-encoding')
const m = require('./messages')
const { COMMANDS: HYPERDHT_COMMANDS } = require('./constants')

module.exports = class Plugin {
  constructor(name, version) {
    this.name = name
    this.version = version
    this.dht = null
  }

  onregister(dht) {
    this.dht = dht
  }

  onrequest(req, outerReq) {
    throw new Error('onrequest() must be implemented')
  }

  onpersistent() {
    throw new Error('onpersistent() must be implemented')
  }

  destroy() {
    throw new Error('destroy() must be implemented')
  }

  request({ token = null, command, target = null, value = null }, to, opts) {
    const req = c.encode(m.pluginRequest, {
      plugin: this.name,
      version: this.version,
      command,
      value
    })

    return this.dht.request(
      {
        token,
        target,
        command: HYPERDHT_COMMANDS.PLUGIN,
        value: req
      },
      to,
      opts
    )
  }

  query({ command, target = null, value = null }, opts) {
    const req = c.encode(m.pluginRequest, {
      plugin: this.name,
      version: this.version,
      command,
      value
    })

    return this.dht.query(
      {
        target,
        command: HYPERDHT_COMMANDS.PLUGIN,
        value: req
      },
      opts
    )
  }
}