This router utility generates all the different route configurations required by our stack (React Router, Express routing etc.) and URLs.
URL definitions are comprised of key/value pairs:
// app/utils/route-config.js
import routing from '@festicket/route-manager';
export const { getUrl, getPattern, getAllPatterns } = routing({
home: '/',
search: '/search',
foo: '/baz/:bar1/:bar2'
});
We can generate URLs by referring to them using the format key
:
import { getUrl } from 'app/utils/route-config';
// Generate a simple url with no route params
const homeUrl = getUrl('home');
// returns => '/'
// Generate a complex url with many route params
const complexUrl = getUrl('foo', { bar1: 'test-1', bar2: 'test-2' });
// returns => '/baz/test-1/test-2'
// Generate a url with a query
const searchUrl = getUrl('search', {}, { q: 'something' });
// returns => '/search?q=something'
We can generate URL patterns by referring to them by key
:
import { getPattern } from 'app/utils/route-config';
// Generate the home pattern
const homePattern = getPattern('home');
// returns => '/'
const complexPattern = getPattern('foo');
// returns /baz/:bar1/bar2
If you need a relative url you can pass a param to getPattern
:
const complexPattern = getPattern('foo', true);
// returns baz/:bar1/bar2
We can get all patterns (useful for debugging) by calling getAllPatterns
:
import { getAllPatterns } from 'app/utils/route-config';
const patterns = getAllPatterns();
// returns => { home: '/', search: '/search', foo: '/baz/:bar1/:bar2' }
If you need a relative url you can pass a param to getAllPatterns
:
const patterns = getAllPatterns(true);
// returns => { home: '/', search: 'search', foo: 'baz/:bar1/:bar2' }
We can get named params as an object by calling getParams
:
import { getParams } from 'app/utils/route-config';
const params = getParams('festivals/creamfields/2018/shop');
// returns => { festivalSeries: 'creamfields', festivalEdition: '2018' }