Refactor Peer constructor

This commit is contained in:
Prathamesh Musale 2023-02-10 13:14:31 +05:30
parent 87aed42d50
commit 3d8451feca

View File

@ -13,7 +13,7 @@ import { pushable, Pushable } from 'it-pushable';
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';
import { toString as uint8ArrayToString } from 'uint8arrays/to-string';
import { webRTCDirect, WebRTCDirectComponents, P2P_WEBRTC_STAR_ID, WebRTCDirectNodeType } from '@cerc-io/webrtc-direct';
import { webRTCDirect, WebRTCDirectComponents, P2P_WEBRTC_STAR_ID, WebRTCDirectNodeType, WebRTCDirectInit } from '@cerc-io/webrtc-direct';
import { noise } from '@chainsafe/libp2p-noise';
import { mplex } from '@libp2p/mplex';
import type { Transport } from '@libp2p/interface-transport';
@ -48,17 +48,13 @@ export class Peer {
const relayPeerId = this._relayNodeMultiaddr.getPeerId();
assert(relayPeerId);
// Instantiation in nodejs.
if (nodejs) {
this._wrtcTransport = webRTCDirect({
wrtc,
enableSignalling: true,
nodeType: WebRTCDirectNodeType.Peer,
relayPeerId
});
} else {
this._wrtcTransport = webRTCDirect({ relayPeerId, enableSignalling: true });
}
const initOptions: WebRTCDirectInit = {
wrtc: nodejs ? wrtc : undefined, // Instantiation in nodejs
enableSignalling: true,
nodeType: WebRTCDirectNodeType.Peer,
relayPeerId
};
this._wrtcTransport = webRTCDirect(initOptions);
}
get peerId (): PeerId | undefined {
@ -161,7 +157,7 @@ export class Peer {
// Listen for pubsub messages
this._node.pubsub.addEventListener('message', (evt) => {
this._handleMessage(evt.detail);
this._handlePubSubMessage(evt.detail);
});
}
@ -304,7 +300,8 @@ export class Peer {
// Log connected peer
console.log(`Connected to ${remotePeerId.toString()} using multiaddr ${connection.remoteAddr.toString()}`);
// Manage connections and stream if peer id is smaller to break symmetry
// Manage connections and streams
// Check if peer id is smaller to break symmetry
if (this._node.peerId.toString() < remotePeerId.toString()) {
const remoteConnections = this._node.getConnections(remotePeerId);
@ -443,7 +440,7 @@ export class Peer {
this._peerStreamMap.set(peerId.toString(), messageStream);
}
_handleMessage (msg: Message): void {
_handlePubSubMessage (msg: Message): void {
// Messages should be signed since globalSignaturePolicy is set to 'StrictSign'
assert(msg.type === 'signed');