Skip to content

Instantly share code, notes, and snippets.

@mjurincic
Forked from nodkz/routes.js
Created January 28, 2017 16:19
Show Gist options
  • Save mjurincic/b9035a45a6669af92da64e1ed809629d to your computer and use it in GitHub Desktop.
Save mjurincic/b9035a45a6669af92da64e1ed809629d to your computer and use it in GitHub Desktop.
import React from 'react';
import Relay from 'react-relay';
import { relayStore } from 'app/clientStores'; // relayStore = Relay.Store;
import App from 'app/_components/App/App';
import Menu from 'app/Menu/Menu';
import MainPage from 'app/MainPage/MainPage';
import Page404 from 'app/_components/Page404/Page404';
import LoadingPage from 'app/_components/LoadingPage/LoadingPage';
import BrokenPage from 'app/_components/BrokenPage/BrokenPage';
import cv from 'app/cv/routes.js';
import job from 'app/job/routes.js';
import company from 'app/company/routes.js';
import misc from 'app/misc/routes.js';
import crm from 'app/crm/routes';
import admin from 'app/adm/routes';
import user from 'app/user/routes';
const route404 = {
path: '*',
component: Page404,
};
class ViewerRoute extends Relay.Route {
static routeName = 'Viewer';
static queries = {
viewer: () => Relay.QL`query { viewer }`,
};
}
const routes = [
{
path: '/',
component: App,
indexRoute: {
component: MainPage,
queries: ViewerRoute, // if I found key `queries` then I wrap `component` with RelayRenderer via `addLoaderForRelayComponents` see below
},
childRoutes: [
cv,
job,
company,
misc,
crm,
admin,
user,
{
path: '/login',
onEnter: (nextState, replace) => {
return replace('user/login');
},
},
route404,
],
},
];
function addLoaderForRelayComponents(routeList) {
function addLoader(route) {
if (route.queries && route.component) {
const component = route.component;
route.component = (propsFromRoute) => (
<Relay.Renderer
Container={component}
environment={relayStore}
queryConfig={new route.queries(route.prepareParams
? route.prepareParams(propsFromRoute.params, propsFromRoute)
: propsFromRoute.params
)}
render={({ error, props }) => {
if (error) {
return <BrokenPage message={error.message} />;
} else if (props) {
return React.createElement(component, {...propsFromRoute, ...props });
}
return <LoadingPage />;
}}
/>
);
}
}
routeList.forEach(route => {
if (route.indexRoute) {
addLoader(route.indexRoute);
}
addLoader(route);
if (route.childRoutes && Array.isArray(route.childRoutes)) {
addLoaderForRelayComponents(route.childRoutes);
}
});
}
// one time scan for routes for replacing component by StatelessComponent with Relay.Renderer inside
addLoaderForRelayComponents(routes);
export default routes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment