Skip to content

Instantly share code, notes, and snippets.

Last active Dec 31, 2021
What would you like to do?
const fetchResultViaPeer = async (peer, query) => {
if ( == libp2p.peerId) return // Don't send the query to ourself. This shouldn't happen in the first place, right?
if (!peer.protocols.includes(ConstellationProtocols.PROTOCOL)) return // Only contact peers that are in the Wham-Bam constellation
const connection = window.libp2p.connectionManager.get(
if (!connection) return
console.log(`[FETCH VIA PEER] PIPE Sending Query to peer ID: ${}`)
const { stream } = await connection.newStream([ConstellationProtocols.PROTOCOL])
const result = await pipe(
// Source data
// Write to the stream, and pass its output to the next function
// Sink function
async function collect (source) {
const vals = []
// For each chunk of data
for await (const val of source) {
// Output the data
console.log('[Fetch Via Peer PIPE] received stream response:', vals.toString())
return vals
// return data.toString();
return vals
const hackResult = await result.toString().split('///WTF-EOF')[0]
console.log('[FETCHED VIA PEER] Result: ', hackResult)
return hackResult
// Send request to all connected peers and take the first responder.
let peerRequestsPromises = [];
window.libp2p.peerStore.peers.forEach(peer =>
peerRequestsPromises.push(fetchResultViaPeer(peer, payload))
const resBody = await Promise.any(peerRequestsPromises);
async function fetcher(query) {
console.log(`[fetcher()] Started query:${query}&format=json`)
const resp = await fetch(`${query}&format=json`)
const text = await resp.text();
console.log(`[fetcher()] Received text: ${text}`)
return text + "///WTF-EOF -------------------------------------------------------" // HACK because I can't figure out why libp2p stream is truncating
async function handler ({ connection, stream }) {
await pipe(
async function collect (source) {
const vals = []
for await (const val of source) {
return vals
async function executeSearch (source) {
const query = await source
const result = []
const fetchResult = await fetcher(query.toString())
console.log(`My Reply back is: ${result}`)
const retRes = [[result],[]] //hack attempt didn't work, result still truncated
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment