diff --git a/src/services/memo-post.js b/src/services/memo-post.js index 12b1a90..3a27adf 100644 --- a/src/services/memo-post.js +++ b/src/services/memo-post.js @@ -45,15 +45,7 @@ class MemoPost { // Resolves with the transaction id, or rejects with a typed error. async post (message) { const check = this.validate(message) - if (!check.ok) { - const err = new Error( - check.type === 'length' - ? `Memo is too long. Maximum is ${MAX_MEMO_CHARS} characters.` - : 'Memo must not be empty.' - ) - err.code = check.type === 'length' ? 'memo_length' : 'memo_validation' - throw err - } + this._throwIfInvalid(check) if (!this.wallet) { throw new Error('Memo post requires a wallet.') @@ -71,6 +63,26 @@ class MemoPost { ) // Reflect the new post in the feed once broadcast succeeds. + this._reflectPost(txid, message) + + return txid + } + + // Throw the appropriate typed error when a memo fails validation. + _throwIfInvalid (check) { + if (check.ok) return + + const err = new Error( + check.type === 'length' + ? `Memo is too long. Maximum is ${MAX_MEMO_CHARS} characters.` + : 'Memo must not be empty.' + ) + err.code = check.type === 'length' ? 'memo_length' : 'memo_validation' + throw err + } + + // Record the new post on the injected feed when one is present. + _reflectPost (txid, message) { if (this.feed && typeof this.feed.addPost === 'function') { this.feed.addPost({ txid, @@ -78,8 +90,6 @@ class MemoPost { text: message }) } - - return txid } } diff --git a/test/unit/memo-post.test.js b/test/unit/memo-post.test.js index 1a5fef2..314da82 100644 --- a/test/unit/memo-post.test.js +++ b/test/unit/memo-post.test.js @@ -89,26 +89,17 @@ test('posting an empty memo throws a validation error and broadcasts nothing', a assert.equal(feed.posts.length, 0) }) -test('posting a whitespace-only memo throws a validation error and broadcasts nothing', async () => { - const wallet = fakeWallet() - const memoPost = new MemoPost({ wallet }) +test('posting a whitespace-only or non-string memo throws a validation error and broadcasts nothing', async () => { + for (const invalid of [' ', 42]) { + const wallet = fakeWallet() + const memoPost = new MemoPost({ wallet }) - await assert.rejects( - memoPost.post(' '), - (err) => err.code === 'memo_validation' - ) - assert.equal(wallet.broadcasts.length, 0) -}) - -test('posting a non-string memo throws a validation error', async () => { - const wallet = fakeWallet() - const memoPost = new MemoPost({ wallet }) - - await assert.rejects( - memoPost.post(42), - (err) => err.code === 'memo_validation' - ) - assert.equal(wallet.broadcasts.length, 0) + await assert.rejects( + memoPost.post(invalid), + (err) => err.code === 'memo_validation' + ) + assert.equal(wallet.broadcasts.length, 0) + } }) test('posting an over-long memo (218) throws a length error and broadcasts nothing', async () => {