Skip to content

Instantly share code, notes, and snippets.

@quicksnap
Created May 8, 2018 20:21
Show Gist options
  • Save quicksnap/0db9dc55d1a7122e8f629e8b421b35b5 to your computer and use it in GitHub Desktop.
Save quicksnap/0db9dc55d1a7122e8f629e8b421b35b5 to your computer and use it in GitHub Desktop.
// 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