Skip to content

Commit 78d96d0

Browse files
feat: create b58 string on creation and throw on id mutation
1 parent bebb0a7 commit 78d96d0

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

src/index.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class PeerId {
1818
}
1919

2020
this._id = id
21-
this._idB58String = ''
21+
this._idB58String = mh.toB58String(this.id)
2222
this._privKey = privKey
2323
this._pubKey = pubKey
2424
}
@@ -27,6 +27,10 @@ class PeerId {
2727
return this._id
2828
}
2929

30+
set id (val) {
31+
throw new Error('Id is immutable')
32+
}
33+
3034
get privKey () {
3135
return this._privKey
3236
}
@@ -82,10 +86,6 @@ class PeerId {
8286
}
8387

8488
toB58String () {
85-
if (!this._idB58String) {
86-
this._idB58String = mh.toB58String(this.id)
87-
}
88-
8989
return this._idB58String
9090
}
9191
}

test/index.spec.js

+11
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,17 @@ describe('PeerId', () => {
2929
})
3030
})
3131

32+
it('throws on changing the id', (done) => {
33+
PeerId.create((err, id) => {
34+
expect(err).to.not.exist
35+
expect(id.toB58String().length).to.equal(46)
36+
expect(() => {
37+
id.id = new Buffer('hello')
38+
}).to.throw(/immutable/)
39+
done()
40+
})
41+
})
42+
3243
it('recreate an Id from Hex string', () => {
3344
const id = PeerId.createFromHexString(testIdHex)
3445
expect(testIdBytes).to.deep.equal(id.id)

0 commit comments

Comments
 (0)