Skip to content

Instantly share code, notes, and snippets.

@pfrazee
Forked from RangerMauve/DatArchive.dream.js
Last active August 27, 2019 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfrazee/4d4c1fac0e2df1aeb45185aa52332841 to your computer and use it in GitHub Desktop.
Save pfrazee/4d4c1fac0e2df1aeb45185aa52332841 to your computer and use it in GitHub Desktop.
Dream DatArchive API for extensions / peers
const archive = await DatArchive.load('someurl')
var fooExt = archive.extension('foo')
// listen to 'foo' messages from all peers
fooExt.addEventListener('message', ({detail}) => {
const {message, peer} = detail
// send to one peer:
await peer.extension('bar').send('Hello World')
// send to all peers
await archive.extension('bar').broadcast('Hello world')
const decoder = new TextDecoder()
// Message is always an ArrayBuffer
const decoded = decoder.decode(message)
console.log('got message from peer', type, message, peer.id)
})
// Get currently connected peers
const peers = await archive.peers.list()
for (let peer of peers) {
// send to one peer
await peer.extension('foo').send('Hey, world?')
// listen to one peer
peer.extension('foo').addEventListener('message', ...)
}
// Broadcast to all peers
await archive.extension('foo').broadcast('Hey, world?')
// Similar to the hyperdrive API
// https://github.com/mafintosh/hyperdrive#archiveonpeer-add-peer
archive.peers.addEventListener('add', ({detail}) => {
const { peer } = detail
await peer.extension('example').send('example')
})
const archive = await DatArchive.load('someurl')
archive.registerExtension('foo')
archive.registerExtension('bar')
// listen to 'foo' messages from all peers
archive.addEventListener('extension-message', ({detail}) => {
const {type, message, peer} = detail
if(type === 'foo') {
// send to one peer:
await peer.sendExtension('bar', 'Hello World')
// send to all peers
await archive.broadcastExtension('bar', 'Hello world')
}
const decoder = new TextDecoder()
// Message is always an ArrayBuffer
const decoded = decoder.decode(message)
console.log('got message from peer', type, message, peer.id)
})
// Get currently connected peers
const peers = await archive.peers.list()
for (let peer of peers) {
// send to one peer
await peer.sendExtension('foo', 'Hey, world?')
// listen to one peer
peer.addEventListener('extension-message', ...)
}
// Broadcast to all peers
await archive.broadcastExtension('foo', 'Hey, world?')
// Similar to the hyperdrive API
// https://github.com/mafintosh/hyperdrive#archiveonpeer-add-peer
archive.peers.addEventListener('add', ({detail}) => {
const { peer } = detail
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment