Skip to content

Commit 19a3940

Browse files
authored
feat: add decapsulateCode method (#98)
* feat: add decapsulateCode method This allows users to remove the last index of a given protocol code. It behaves like decapsulate, but checks protocol codes rather than string matching the whole multiaddr
1 parent 3681086 commit 19a3940

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/index.js

+28
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,34 @@ Multiaddr.prototype.decapsulate = function decapsulate (addr) {
237237
return Multiaddr(s.slice(0, i))
238238
}
239239

240+
/**
241+
* A more reliable version of `decapsulate` if you are targeting a
242+
* specific code, such as 421 (the `p2p` protocol code). The last index of the code
243+
* will be removed from the `Multiaddr`, and a new instance will be returned.
244+
* If the code is not present, the original `Multiaddr` is returned.
245+
*
246+
* @param {Number} code The code of the protocol to decapsulate from this Multiaddr
247+
* @return {Multiaddr}
248+
* @example
249+
* const addr = Multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
250+
* // <Multiaddr 0400... - /ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC>
251+
*
252+
* addr.decapsulateCode(421).toString()
253+
* // '/ip4/0.0.0.0/tcp/8080'
254+
*
255+
* Multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()
256+
* // '/ip4/127.0.0.1/tcp/8080'
257+
*/
258+
Multiaddr.prototype.decapsulateCode = function decapsulateCode (code) {
259+
const tuples = this.tuples()
260+
for (let i = tuples.length - 1; i >= 0; i--) {
261+
if (tuples[i][0] === code) {
262+
return Multiaddr(codec.tuplesToBuffer(tuples.slice(0, i)))
263+
}
264+
}
265+
return this
266+
}
267+
240268
/**
241269
* Extract the peerId if the multiaddr contains one
242270
*

test/index.spec.js

+16
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,22 @@ describe('helpers', () => {
598598
})
599599
})
600600

601+
describe('.decapsulateCode', () => {
602+
it('removes the last occurrence of the code from the multiaddr', () => {
603+
const relayTCP = multiaddr('/ip4/0.0.0.0/tcp/8080')
604+
const relay = relayTCP.encapsulate('/p2p/QmZR5a9AAXGqQF2ADqoDdGS8zvqv8n3Pag6TDDnTNMcFW6/p2p-circuit')
605+
const target = multiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
606+
const original = relay.encapsulate(target)
607+
expect(original.decapsulateCode(421)).to.eql(relay)
608+
expect(relay.decapsulateCode(421)).to.eql(relayTCP)
609+
})
610+
611+
it('ignores missing codes', () => {
612+
const tcp = multiaddr('/ip4/0.0.0.0/tcp/8080')
613+
expect(tcp.decapsulateCode(421)).to.eql(tcp)
614+
})
615+
})
616+
601617
describe('.equals', () => {
602618
it('returns true for equal addresses', () => {
603619
const addr1 = multiaddr('/ip4/192.168.0.1')

0 commit comments

Comments
 (0)