Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Created September 1, 2016 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelrinaldi/99091dbc01971c367b2cd5401103594b to your computer and use it in GitHub Desktop.
Save rafaelrinaldi/99091dbc01971c367b2cd5401103594b to your computer and use it in GitHub Desktop.
Simple routes resolver
import settings from '../settings';
const {routes} = settings;
const {basePath} = routes;
/*
* Route path resolver.
* Read routes from the settings file.
*
* - id: route identifier (or alias)
* - values: optional sequential list of params substitutions
*
* Examples:
*
* const routes = {beep: '/beep/:a/:b', bop: '/bop'};
*
* route('beep'); // => /beep/:a/:b
* route('beep', 'foo'); // => /beep/foo/:b
* route('beep', 'foo', 'bar'); // => /beep/foo/bar
* route('bop'); // /bop
*/
const route = (id, ...values) => {
const path = `${basePath}${routes[id]}`;
const params = path.match(/\:\w+/gm) || [];
return params.reduce((previous, next, index) => {
return previous.replace(next, values[index] || next);
}, path);
};
export default route;
// Special named export for urls that are not affected by `basePath`
export const external = id => routes.external[id];
export default {
routes: {
// Base path for all the routes
basePath: '',
// Root path
home: '/',
// Path for every article detail
article: '/article/:slug',
// Path for every content landing (Guide, 101, etc)
articles: '/articles/:slug',
// Path for glossary index
glossary: '/glossary',
// Path for glossary definition detail
glossaryDetail: '/glossary/:slug',
// Path for the plans page
plans: '/plans',
// Path for the plans page with the madlibs active
quote: '/plans/quote',
// Logged in
forms: '/forms',
login: '/auth/login',
// External
external: {
blog: 'http://blog.thing.com',
facebook: 'https://www.facebook.com/ThingOfficial',
instagram: 'https://instagram.com/thingofficial',
twitter: 'https://twitter.com/thingofficial',
youtube: 'https://www.youtube.com/user/ThingOfficial',
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment