Skip to content

Commit a99bae2

Browse files
dmitriy ryajovdmitriy ryajov
authored andcommitted
feat: added getPeerId method to extract the peer id from the address
1 parent 0daf0e3 commit a99bae2

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,4 @@
6060
"greenkeeper[bot] <greenkeeper[bot]@users.noreply.github.com>",
6161
"npm-to-cdn-bot (by Forbes Lindesay) <npmcdn-to-unpkg-bot@users.noreply.github.com>"
6262
]
63-
}
63+
}

src/index.js

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const extend = require('xtend')
55
const codec = require('./codec')
66
const protocols = require('./protocols-table')
77
const varint = require('varint')
8+
const bs58 = require('bs58')
89

910
const NotImplemented = new Error('Sorry, Not Implemented Yet.')
1011

@@ -83,8 +84,8 @@ Multiaddr.prototype.toOptions = function toOptions () {
8384
*/
8485
Multiaddr.prototype.inspect = function inspect () {
8586
return '<Multiaddr ' +
86-
this.buffer.toString('hex') + ' - ' +
87-
codec.bufferToString(this.buffer) + '>'
87+
this.buffer.toString('hex') + ' - ' +
88+
codec.bufferToString(this.buffer) + '>'
8889
}
8990

9091
/**
@@ -105,7 +106,7 @@ Multiaddr.prototype.inspect = function inspect () {
105106
Multiaddr.prototype.protos = function protos () {
106107
return map(this.protoCodes(), function (code) {
107108
return extend(protocols(code))
108-
// copy to prevent users from modifying the internal objs.
109+
// copy to prevent users from modifying the internal objs.
109110
})
110111
}
111112

@@ -231,6 +232,33 @@ Multiaddr.prototype.decapsulate = function decapsulate (addr) {
231232
return Multiaddr(s.slice(0, i))
232233
}
233234

235+
/**
236+
* Extract the peerId if the multiaddr contains one
237+
*
238+
* @return {String} peerId - The id of the peer
239+
* @example
240+
* const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')
241+
* // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string>
242+
*
243+
* const peerId
244+
*
245+
* try {
246+
* peerId = mh1.getPeerId()
247+
* } catch (err) {
248+
* // not a valid base58 address
249+
* }
250+
*/
251+
Multiaddr.prototype.getPeerId = function peerId () {
252+
let b58str = this.stringTuples().filter((tuple) => {
253+
if (tuple[0] === protocols.names['ipfs'].code) {
254+
return true
255+
}
256+
})[0][1]
257+
258+
bs58.decode(b58str)
259+
return b58str
260+
}
261+
234262
/**
235263
* Checks if two Multiaddrs are the same
236264
*
@@ -428,4 +456,3 @@ Multiaddr.resolve = function resolve (addr, callback) {
428456
*/
429457
return callback(new Error('not implemented yet'))
430458
}
431-

0 commit comments

Comments
 (0)