Skip to content

Commit

Permalink
fix: json round trip works as expected (#85)
Browse files Browse the repository at this point in the history
* fix: implement JSON so roundtrip works as expected

This commit adds a test case, and simply reuses the
the `toString` implementation.

* style: remove semicolon to pass lint
  • Loading branch information
jchris authored and jacobheun committed Mar 4, 2019
1 parent 250dd0f commit 1977874
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ Multiaddr.prototype.toString = function toString () {
return codec.bufferToString(this.buffer)
}

/**
* Returns Multiaddr as a JSON encoded object
*
* @returns {String}
* @example
* JSON.stringify(Multiaddr('/ip4/127.0.0.1/tcp/4001'))
* // '/ip4/127.0.0.1/tcp/4001'
*/
Multiaddr.prototype.toJSON = Multiaddr.prototype.toString

/**
* Returns Multiaddr as a convinient options object to be used with net.createConnection
*
Expand Down
5 changes: 5 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ describe('construction', () => {
expect(multiaddr(udpAddr).buffer).to.deep.equal(udpAddr.buffer)
})

it('reconstruct with JSON', () => {
expect(multiaddr(JSON.parse(JSON.stringify(udpAddr))).buffer === udpAddr.buffer).to.equal(false)
expect(multiaddr(JSON.parse(JSON.stringify(udpAddr))).buffer).to.deep.equal(udpAddr.buffer)
})

it('empty construct still works', () => {
expect(multiaddr('').toString()).to.equal('/')
})
Expand Down

0 comments on commit 1977874

Please sign in to comment.