From 3ea476e2f2941b38bb147cfec08052636dc39a14 Mon Sep 17 00:00:00 2001 From: Federico Weber Date: Tue, 22 Jan 2019 16:49:26 -0800 Subject: [PATCH] don't call FETCH_SUCCESS on error This is needed so that in case of errors we can handle it in the `FETCH_FAIL` handler, without worring about protecting the `FETCH_SUCCESS` from missing or malformed data. This is needed to properly handle RPC errors in the front-end in https://github.com/bufferapp/buffer-analyze/pull/337 --- src/middleware.js | 24 ++++++++++++++---------- test/middleware.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/middleware.js b/src/middleware.js index 60cb548..f02460e 100644 --- a/src/middleware.js +++ b/src/middleware.js @@ -24,16 +24,20 @@ export default store => { rpc .call(action.name, args) - .then(result => - store.dispatch( - actions.fetchSuccess({ - name: action.name, - args, - id, - result, - }), - ), - ) + .then(result => { + console.log(result) + + if (result) { + store.dispatch( + actions.fetchSuccess({ + name: action.name, + args, + id, + result, + }), + ) + } + }) .catch(error => { console.error(error) // eslint-disable-line store.dispatch( diff --git a/test/middleware.test.js b/test/middleware.test.js index 8cbfc75..ec867e9 100644 --- a/test/middleware.test.js +++ b/test/middleware.test.js @@ -141,4 +141,31 @@ describe('middleware', () => { error: RPCClient.fakeError, }) }) + it('should not dispatch a FETCH_SUCCESS action on error', async () => { + const store = { + dispatch: jest.fn(), + getState: () => ({ + asyncDataFetch: {}, + }), + } + const name = 'fail' + const args = { + test: 'yes', + } + const action = { + type: actionTypes.FETCH, + name, + args, + } + middleware(store)(() => {})(action) + await sleep() // give the event loop a chance to process promise + expect(store.dispatch).toHaveBeenCalledTimes(2) + expect(store.dispatch).toHaveBeenLastCalledWith({ + type: `${name}_${actionTypes.FETCH_FAIL}`, + name, + args, + id: 0, + error: RPCClient.fakeError, + }) + }) })