import { compile , PathFunction } from 'path-to-regexp' ; import { stringify } from 'query-string' ; import { RouterState , RouterStore } from '../stores' ; interface GeneratorCache { [ pattern ] : PathFunction ; } const generatorCache = { } ; const getGenerator = ( pattern ) : PathFunction => { const generator = generatorCache [ pattern ] ; if ( generator ) { return generator ; } const compiledGenerator = compile ( pattern ) ; generatorCache [ pattern ] = compiledGenerator ; return compiledGenerator ; } ; /**
 * Generates a URL from a pattern and parameters.
 * For example,
 *     generateUrl('/departments/:id', { id: 'electronics' })
 *     => '/departments/electronics'
 */ export const generateUrl = ( pattern = '/' , params = { } , queryParams = { } , queryStringifyOptions ? ) => { const generator = getGenerator ( pattern ) ; let url = generator ( params ) ; if ( Object . keys ( queryParams ) . length > 0 ) { url = `${ url }?${ stringify ( queryParams , queryStringifyOptions ) }` ; } return url ; } ; param { RouterStore } routerStore param { RouterState } routerState returns { string } export const routerStateToUrl = ( routerStore , routerState ) : string => { const { routeName , params , queryParams , options } = routerState ; let route = routerStore . getRoute ( routeName ) ; if ( ! route ) { route = routerStore . getNotFoundRoute ( ) ; } return generateUrl ( route . pattern , params , queryParams , options . queryStringifyOptions ) ; } ;