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> {
const res = await selectPeerForProtocol(
const { peer } = await selectPeerForProtocol(
this.peerStore,
[this.multicodec],
peerId
);
if (!res) {
throw new Error(`Failed to select peer for ${this.multicodec}`);
}
return res.peer;
return peer;
}
async peers(): Promise<Peer[]> {

View File

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

View File

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