@metabin/gate

2.4.1 • Public • Published

Metabin Gate

Schema-driven IPFS pubsub chanels.

Installation

> npm install @metabin/gate --save
> yarn add @metabin/gate
<script src="https://unpkg.com/@metabin/gate/dist/umd.js"></script>

Usage

Metabin Gate can be used as a wrapper around any ipfs-interface-core compatible module. Probably you will want to use it with js-ipfs or js-ipfs-api modules.

const Ipfs = require('ipfs') 
const metabinGate = require('@metabin/gate')

const schema = {
  type: 'object',
  properties: {
    field: {
      type: 'number'
    }
  }
}

const ipfsNode = new Ipfs({ EXPERIMENTAL: { pubsub: true } })

const handleReceived = (instance, cid, from) => {
  console.log(instance)
  //  {
  //    field: 10
  //  }
}

ipfsNode.on('ready', async () => {
  const gate = await metabinGate.openGate(ipfsNode, schema)
  const stopListener = gate.listen(handleReceived)
  await gate.send({ field: 10 })
  stopListener()
})

Validation

Received instances should be validated against schema as it's possible to broadcast invalid instances if original schema or cid is known. Example below uses Avj but you are free to use any validation tool.

const Ipfs = require('ipfs') 
const metabinGate = require('@metabin/gate')

const Ajv = require('ajv')
const ajv = new Ajv()

const schema = {
  type: 'object',
  properties: {
    field: {
      type: 'number'
    }
  }
}

const validateInstance = (instance) => {
  return ajv.validate(schema, data);  
}

const handleReceived = (instance, cid, from) => {
  const valid = validateInstance(instance)
  if (valid) {
    // valid instance received
  } else {
    // invalid instance received
  }
}

ipfsNode.on('ready', async () => {
  const gate = await metabinGate.openGate(ipfsNode, schema)
  const stopListener = gate.listen(handleReceived)
  await gate.send({ field: 10 })
  stopListener()
})

License

MIT

Package Sidebar

Install

npm i @metabin/gate

Weekly Downloads

1

Version

2.4.1

License

MIT

Unpacked Size

85.5 kB

Total Files

7

Last publish

Collaborators

  • negamaxi