Skip to content

Instantly share code, notes, and snippets.

@abhiaiyer91
Last active November 17, 2017 10:50
Show Gist options
  • Save abhiaiyer91/f84e4accbafd19d646001d57a4278ca1 to your computer and use it in GitHub Desktop.
Save abhiaiyer91/f84e4accbafd19d646001d57a4278ca1 to your computer and use it in GitHub Desktop.
/**
* A redux middleware for processing Meteor methods
* When an action is dispatched, it will pass through our middleware.
* if denoted a method, we will dispatch the action with readyState of loading
* The method passed in is then called, and dispatches further ready states for success/error
* The reducer shape should include { data, readyState } for use in the UI
* @returns {Function}
*/
export default function methodMiddleware() {
return (next) => {
return (action) => {
const { method, ...rest } = action;
if (!method) {
return next(action);
}
next({ ...rest, readyState: 'loading' });
return method((error, result) => {
if (error) {
Errors.handler(error);
return next({ error: error.reason, readyState: 'error', ...rest });
}
return next({ data: result, readyState: 'success', ...rest});
});
};
};
}
// implementation
Store.dispatch({
type: "SOMETIHNG",
method: function (cb) {
return Meteor.call('something', cb);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment