Skip to content

Commit 1977874

Browse files
jchrisjacobheun
authored andcommittedMar 4, 2019
fix: json round trip works as expected (#85)
* 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
1 parent 250dd0f commit 1977874

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed
 

‎src/index.js

+10
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ Multiaddr.prototype.toString = function toString () {
5656
return codec.bufferToString(this.buffer)
5757
}
5858

59+
/**
60+
* Returns Multiaddr as a JSON encoded object
61+
*
62+
* @returns {String}
63+
* @example
64+
* JSON.stringify(Multiaddr('/ip4/127.0.0.1/tcp/4001'))
65+
* // '/ip4/127.0.0.1/tcp/4001'
66+
*/
67+
Multiaddr.prototype.toJSON = Multiaddr.prototype.toString
68+
5969
/**
6070
* Returns Multiaddr as a convinient options object to be used with net.createConnection
6171
*

‎test/index.spec.js

+5
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ describe('construction', () => {
3636
expect(multiaddr(udpAddr).buffer).to.deep.equal(udpAddr.buffer)
3737
})
3838

39+
it('reconstruct with JSON', () => {
40+
expect(multiaddr(JSON.parse(JSON.stringify(udpAddr))).buffer === udpAddr.buffer).to.equal(false)
41+
expect(multiaddr(JSON.parse(JSON.stringify(udpAddr))).buffer).to.deep.equal(udpAddr.buffer)
42+
})
43+
3944
it('empty construct still works', () => {
4045
expect(multiaddr('').toString()).to.equal('/')
4146
})

0 commit comments

Comments
 (0)