Last active
September 29, 2022 15:25
-
-
Save oxyflour/7a445c7a0b77f01576f6dacd977b49bf to your computer and use it in GitHub Desktop.
ipfs pubsub webrtc star
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipfs from 'ipfs' | |
function $e<K extends keyof HTMLElementTagNameMap>(tag: K, props = { } as { [key: string]: any }, children = [] as any[]) { | |
const e = document.createElement(tag) | |
for (const [key, val] of Object.entries(props)) { | |
(e as any)[key] = val | |
} | |
for (const [key, val] of Object.entries(props.style || { })) { | |
(e.style as any)[key] = val | |
} | |
for (const [key, val] of Object.entries(props.attrs || { })) { | |
e.setAttribute(key, val as any) | |
} | |
for (const child of children) { | |
e.appendChild(child) | |
} | |
return e | |
} | |
async function main() { | |
const $id = $e('h1', { textContent: 'loading...' }) | |
document.body.appendChild($id) | |
const node = await ipfs.create({ | |
repo: `ipfs-${Math.random()}`, | |
config: { | |
Addresses: { | |
Swarm: [ | |
// https://github.com/libp2p/js-libp2p-webrtc-star | |
'/dns4/aly.yff.me/tcp/3443/wss/p2p-webrtc-star/' | |
] | |
}, | |
// disable bootstraps and use relay | |
relay: { enabled: true, hop: { enabled: true } }, | |
Bootstrap: [ | |
] | |
} as any, | |
}) | |
await node.swarm.connect(multiaddr('/dns4/pc10.yff.me/tcp/4433/wss/ipfs/12D3KooWED3KA3kAanfBh6FLRdUF2ediVEXZ6HNc1oZAkWVQs5dS')) | |
for await (const file of node.ls('QmXinEyeNz6gBmAfi1xVwV8LMDRkGjKhF4D8MFe5Yea6ex')) { | |
console.log(file) | |
} | |
const nodeId = await node.id(), | |
topicId = "pubsub-example-topic" | |
await node.pubsub.subscribe(topicId, msg => { | |
$log.prepend(`${new TextDecoder().decode(msg.data)}\n`) | |
}) | |
async function send() { | |
$send.disabled = true | |
const text = `${nodeId.id}: ${$msg.value}` | |
await node.pubsub.publish(topicId, new TextEncoder().encode(text), { }) | |
$msg.value = '' | |
$send.disabled = false | |
} | |
$id.textContent = nodeId.id | |
const $msg = $e('input'), | |
$send = $e('button', { textContent: 'send', onclick: send }), | |
$input = $e('div', { }, [$msg, $send]), | |
$log = $e('pre') | |
for (const e of [$id, $input, $log]) { | |
document.body.appendChild(e) | |
} | |
} | |
main() | |
.catch(err => { | |
document.body.appendChild($e('div', { textContent: err.message, style: { color: 'red' } })) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment