Skip to content

Instantly share code, notes, and snippets.

@rscarvalho
Created March 24, 2017 14:42
Show Gist options
  • Save rscarvalho/90afb8311c4c8ac8e409413d80703918 to your computer and use it in GitHub Desktop.
Save rscarvalho/90afb8311c4c8ac8e409413d80703918 to your computer and use it in GitHub Desktop.
import { combineEpics } from 'redux-observable';
/*
* Let's assume each configuration has the following:
* {
* type: String|Array<String>,
* url: String,
* method: String,
* body: String|Function<Action, String|Object>,
* process: Function<ActionObservable, ActionObservable>,
* latest: Boolean // true for switchMap
* }
*/
function createApiEpic(configurations) {
var epics = configurations.map(config => {
const actionTypes = Array.isArray(config.type) ? config.type : [config.type];
const requestProcessor = action => {
/* Here you create your ajax observable and do proper handling of request/response */
};
return action$ => {
let stream$ = action$.ofType(actionTypes);
stream$ = config.latest ? stream$.mergeMap(requestProcessor) : stream$.switchMap(requestProcessor);
return typeof config.process === 'function' ? config.process(stream$) : stream$;
}
});
return combineEpics(epics);
}
const ajaxApiEpic = createApiEpic([
{
type: 'SAVE_MY_DATA',
url: `/api/mydata/${myId}`,
method: 'PATCH',
latest: true,
body: action => action.data,
process: actions$ => actions$.debounceTime(400).retry(2)
}
]);
// Then when configuring the middleware
const rootEpic = combineEpics(
ajaxApiEpic,
// ... your other epics
);
const middleware = createEpicMiddleware(rootEpic);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment