Skip to content

Instantly share code, notes, and snippets.

@ricardocasares
Last active August 29, 2018 09:09
Show Gist options
  • Save ricardocasares/3037b009e23c8ad56bdc16fc8d6c76d0 to your computer and use it in GitHub Desktop.
Save ricardocasares/3037b009e23c8ad56bdc16fc8d6c76d0 to your computer and use it in GitHub Desktop.
Resolve redux initial route data
import * as Pattern from "url-pattern";
import { Dispatch, Middleware } from "redux";
export interface Options {
actions: string[];
routes: {
[x: string]: (store: Dispatch, params: any) => any;
};
}
export const resolver = function(options: Options) {
const routes = Object.keys(options.routes).map(route => ({
path: new Pattern(route),
resolve: options.routes[route]
}));
const middleware: Middleware = function middleware(store) {
return next => async action => {
const result = next(action);
if (actions.include(action.type)) {
let path;
let resolve;
let next = 0;
let match = false;
do {
path = routes[next].path;
resolve = routes[next].resolve;
match = path.match(options.selector(action));
++next;
} while (!match && routes[next]);
if (match) {
// we're handling errors inside another middleware,
// so we should NOT wrap this inside try/catch block
await resolve(store.dispatch, match);
}
}
return next(action);
};
};
return middleware;
};
export default resolver;
import { createStore, applyMiddleware } from 'redux';
import resolverMiddleware from './resolver';
import { fetchPost, fetchPosts } from './blog/actions';
const resolver = resolverMiddleware({
actions: ['SOME_ACTION', 'ANOTHER_ACTION'],
selector: action => action.meta.resource,
resolve: {
'/': async (dispatch, params) {
await dispatch(fetchPosts())
},
'/:slug/:id': async (dispatch, params) {
console.log(params.slug)
await dispatch(fetchPost(params.id))
}
}
});
export const configureStore = (initialState) => createStore(reducer, initialState, applyMiddleware(resolver));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment