From 78d96d0b14615b85b898d41375105150c3498851 Mon Sep 17 00:00:00 2001 From: Friedel Ziegelmayer Date: Sun, 18 Dec 2016 09:02:37 +0100 Subject: [PATCH] feat: create b58 string on creation and throw on id mutation --- src/index.js | 10 +++++----- test/index.spec.js | 11 +++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index f220efc..9cf6fb0 100644 --- a/src/index.js +++ b/src/index.js @@ -18,7 +18,7 @@ class PeerId { } this._id = id - this._idB58String = '' + this._idB58String = mh.toB58String(this.id) this._privKey = privKey this._pubKey = pubKey } @@ -27,6 +27,10 @@ class PeerId { return this._id } + set id (val) { + throw new Error('Id is immutable') + } + get privKey () { return this._privKey } @@ -82,10 +86,6 @@ class PeerId { } toB58String () { - if (!this._idB58String) { - this._idB58String = mh.toB58String(this.id) - } - return this._idB58String } } diff --git a/test/index.spec.js b/test/index.spec.js index e4e19b8..5c040a7 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -29,6 +29,17 @@ describe('PeerId', () => { }) }) + it('throws on changing the id', (done) => { + PeerId.create((err, id) => { + expect(err).to.not.exist + expect(id.toB58String().length).to.equal(46) + expect(() => { + id.id = new Buffer('hello') + }).to.throw(/immutable/) + done() + }) + }) + it('recreate an Id from Hex string', () => { const id = PeerId.createFromHexString(testIdHex) expect(testIdBytes).to.deep.equal(id.id)