chore: move error throwing within `selectPeerForProtocol`

As all callers throw upon undefined result.
This commit is contained in:
fryorcraken.eth 2023-01-25 17:34:36 +11:00
parent c85b113df7
commit 7d29ed1d99
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
3 changed files with 11 additions and 19 deletions

View File

@ -268,15 +268,12 @@ class Filter implements IFilter {
} }
private async getPeer(peerId?: PeerId): Promise<Peer> { private async getPeer(peerId?: PeerId): Promise<Peer> {
const res = await selectPeerForProtocol( const { peer } = await selectPeerForProtocol(
this.peerStore, this.peerStore,
[this.multicodec], [this.multicodec],
peerId peerId
); );
if (!res) { return peer;
throw new Error(`Failed to select peer for ${this.multicodec}`);
}
return res.peer;
} }
async peers(): Promise<Peer[]> { async peers(): Promise<Peer[]> {

View File

@ -119,15 +119,12 @@ export class WakuPeerExchange implements IPeerExchange {
* @returns A peer to query * @returns A peer to query
*/ */
private async getPeer(peerId?: PeerId): Promise<Peer> { private async getPeer(peerId?: PeerId): Promise<Peer> {
const res = await selectPeerForProtocol( const { peer } = await selectPeerForProtocol(
this.peerStore, this.peerStore,
[PeerExchangeCodec], [PeerExchangeCodec],
peerId peerId
); );
if (!res) { return peer;
throw new Error(`Failed to select peer for ${PeerExchangeCodec}`);
}
return res.peer;
} }
/** /**

View File

@ -42,22 +42,22 @@ export async function selectPeerForProtocol(
peerStore: PeerStore, peerStore: PeerStore,
protocols: string[], protocols: string[],
peerId?: PeerId peerId?: PeerId
): Promise<{ peer: Peer; protocol: string } | undefined> { ): Promise<{ peer: Peer; protocol: string }> {
let peer; let peer;
if (peerId) { if (peerId) {
peer = await peerStore.get(peerId); peer = await peerStore.get(peerId);
if (!peer) { if (!peer) {
log( throw new Error(
`Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}` `Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`
); );
return;
} }
} else { } else {
const peers = await getPeersForProtocol(peerStore, protocols); const peers = await getPeersForProtocol(peerStore, protocols);
peer = selectRandomPeer(peers); peer = selectRandomPeer(peers);
if (!peer) { if (!peer) {
log("Failed to find known peer that registers protocols", protocols); throw new Error(
return; `Failed to find known peer that registers protocols: ${protocols}`
);
} }
} }
@ -70,11 +70,9 @@ export async function selectPeerForProtocol(
} }
log(`Using codec ${protocol}`); log(`Using codec ${protocol}`);
if (!protocol) { if (!protocol) {
log( throw new Error(
`Peer does not register required protocols: ${peer.id.toString()}`, `Peer does not register required protocols (${peer.id.toString()}): ${protocols}`
protocols
); );
return;
} }
return { peer, protocol }; return { peer, protocol };