Skip to content

Commit

Permalink
feat: add decapsulateCode method (#98)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
jacobheun authored Sep 10, 2019
1 parent 3681086 commit 19a3940
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,34 @@ Multiaddr.prototype.decapsulate = function decapsulate (addr) {
return Multiaddr(s.slice(0, i))
}

/**
* A more reliable version of `decapsulate` if you are targeting a
* specific code, such as 421 (the `p2p` protocol code). The last index of the code
* will be removed from the `Multiaddr`, and a new instance will be returned.
* If the code is not present, the original `Multiaddr` is returned.
*
* @param {Number} code The code of the protocol to decapsulate from this Multiaddr
* @return {Multiaddr}
* @example
* const addr = Multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
* // <Multiaddr 0400... - /ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC>
*
* addr.decapsulateCode(421).toString()
* // '/ip4/0.0.0.0/tcp/8080'
*
* Multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()
* // '/ip4/127.0.0.1/tcp/8080'
*/
Multiaddr.prototype.decapsulateCode = function decapsulateCode (code) {
const tuples = this.tuples()
for (let i = tuples.length - 1; i >= 0; i--) {
if (tuples[i][0] === code) {
return Multiaddr(codec.tuplesToBuffer(tuples.slice(0, i)))
}
}
return this
}

/**
* Extract the peerId if the multiaddr contains one
*
Expand Down
16 changes: 16 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,22 @@ describe('helpers', () => {
})
})

describe('.decapsulateCode', () => {
it('removes the last occurrence of the code from the multiaddr', () => {
const relayTCP = multiaddr('/ip4/0.0.0.0/tcp/8080')
const relay = relayTCP.encapsulate('/p2p/QmZR5a9AAXGqQF2ADqoDdGS8zvqv8n3Pag6TDDnTNMcFW6/p2p-circuit')
const target = multiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
const original = relay.encapsulate(target)
expect(original.decapsulateCode(421)).to.eql(relay)
expect(relay.decapsulateCode(421)).to.eql(relayTCP)
})

it('ignores missing codes', () => {
const tcp = multiaddr('/ip4/0.0.0.0/tcp/8080')
expect(tcp.decapsulateCode(421)).to.eql(tcp)
})
})

describe('.equals', () => {
it('returns true for equal addresses', () => {
const addr1 = multiaddr('/ip4/192.168.0.1')
Expand Down

0 comments on commit 19a3940

Please sign in to comment.