Created
May 8, 2018 20:21
-
-
Save quicksnap/0db9dc55d1a7122e8f629e8b421b35b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import { ERROR_API_MIDDLEWARE } from '../constants/actions'; | |
import { IAppState } from '../stateTypes'; | |
import { Middleware, Dispatch } from 'redux'; | |
/** | |
* Middleware that wraps `redux-pack` so that we may provide an API client factory | |
*/ | |
type Client = any; | |
type CreateClient = ( | |
dispatch: Dispatch<IAppState>, | |
getState: () => IAppState, | |
) => Client; | |
export function createApiMiddleware(createClient: CreateClient): Middleware { | |
return ({ dispatch, getState }) => { | |
const client = createClient(dispatch, getState as any); | |
return (next) => (action: any) => { | |
if (typeof action.api === 'function') { | |
// Stop the middleware chain, continue on with redux-pack, | |
const { api: unused, ...newAction } = action; | |
const apiPromise = action.api(client, getState, dispatch); | |
// Prevent swallowing errors. Log/dispatch any uncaught errors | |
new Promise(async (resolve, reject) => { | |
try { | |
await apiPromise; | |
} catch (e) { | |
console.error(e); | |
dispatch({ | |
type: 'ERROR_API_MIDDLEWARE', | |
error: e.message || e, | |
meta: { oldAction: action.type }, | |
}); | |
} | |
resolve(); | |
}); | |
return dispatch({ | |
...newAction, | |
promise: apiPromise, | |
}); | |
} | |
return next(action); | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment