Skip to content

Instantly share code, notes, and snippets.

@quirinpa
Created August 27, 2015 14:53
Show Gist options
  • Save quirinpa/7be0b079769cc14e0d8d to your computer and use it in GitHub Desktop.
Save quirinpa/7be0b079769cc14e0d8d to your computer and use it in GitHub Desktop.
export default function alsoMiddleware() {
return (next) => (action) => {
if (!action.also) return next(action);
const { also, ...rest } = action;
if (typeof also === 'function') {
const alsoRes = also();
const ret = next(rest);
next(alsoRes);
return ret;
}
const ret = next(rest);
if (Array.isArray(also))
also.forEach(item => next(item));
else
next(also);
return ret;
};
}
export const STATUS = {
success: '@clientMiddleware/success',
failure: '@clientMiddleware/failure'
};
export default function clientMiddlewareCreator(client) {
return () => {
return (next) => (action) => {
if (!action.promise) return next(action);
const { type, onSuccess, onFailure, ...rest } = action;
next({type, ...rest});
return action.promise(client).then(
(payload) => next({
status: STATUS.success,
defer: onSuccess.bind(null, payload),
payload,
type
}), (error) => next({
status: STATUS.failure,
defer: onFailure.bind(null, error),
error,
type
}));
};
};
}
import {defer} from 'lodash';
export default function deferMiddleware({ dispatch, getState }) {
return next => action => {
if (action.defer)
defer(() => {
const newAction = action.defer(getState(), dispatch);
if (newAction) dispatch(newAction);
});
next(action);
};
}
const applyMiddlewares = applyMiddleware(
clientMiddlewareCreator(client),
deferMiddleware,
alsoMiddleware,
waitMiddleware
);
import {delay} from 'lodash';
export default function waitMiddleware({ dispatch, getState }) {
return next => action => {
const { wait, saveWaitID, ...rest } = action;
if (!wait) return next(action);
const timerId = delay(() => dispatch(rest), wait);
if (saveWaitID) saveWaitID(timerId);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment