UNPKG

@rtcio/react

Version:

A wrapper around the @rtcio/core library for React integration

60 lines 2.63 kB
import { usePeerContext } from "./usePeerContext"; import { result } from "@dbidwell94/ts-utils"; export class MultiPeerEmitError extends Error { constructor(peers, eventName) { super("Failed to emit event to peers"); this.peers = peers; this.eventName = eventName; } } export function createUsePeerEmitter() { return function usePeerEmitter() { const ctx = usePeerContext(); if (!ctx) { throw new Error("usePeerEmitter must be called from within a P2PProvider"); } /** * Emits an event to a specific peerId. If the peerId is not connected * or there was an error sending the message, a `Failure` result type will be returned. * * @param toPeer Which peer we want to emit the event to * @param eventName the event we want to emit * @param args All the arguments for the event * * @returns Promise<Result<void>> If emitting was successful, a `Success` variant will be * returned. Otherwise it will be a `Failure` variant */ async function emitTo(toPeer, eventName, ...args) { const peer = ctx.peers.current.get(toPeer); if (!peer) { return result.err(`Peer with id ${toPeer} is not connected`); } return peer.emit(eventName, ...args); } /** * Emits an event to all connected peers. If there was an error sending a message to a peer, * we will continue sending to others and return a `Failure<MultiPeerEmitError>`, which will * contain the eventName which was emitted, as well as any peerId that we failed to send to * * @param eventName The event we want to emit * @param args All the arguments for the event * @returns Promise<Result<void, MultiPeerEmitError>> If emitting was successful, a `Success` * variant will be returned. Otherwise it will be a `Failure<MultiPeerEmitError>` */ async function emit(eventName, ...args) { const failedEmitting = []; for (const peerId of ctx.peerIds) { const res = await emitTo(peerId, eventName, ...args); if (res.isError()) { failedEmitting.push(peerId); } } if (failedEmitting.length > 0) { return result.err(new MultiPeerEmitError(failedEmitting, eventName)); } return result.ok(undefined); } return { emitTo, emit }; }; } //# sourceMappingURL=usePeerEmitter.js.map