2019-12-23 22:20:17 +01:00
|
|
|
import * as pathToRegexp from 'path-to-regexp'
|
|
|
|
|
|
|
|
export { pathToRegexp }
|
2018-02-01 19:54:09 +01:00
|
|
|
|
2019-11-09 23:34:53 +01:00
|
|
|
export default (customRoute = false) => {
|
2019-04-24 16:47:50 +02:00
|
|
|
return (path: string) => {
|
2019-12-23 22:20:17 +01:00
|
|
|
const matcher = pathToRegexp.match(path, {
|
2019-11-27 22:48:28 +01:00
|
|
|
sensitive: false,
|
|
|
|
delimiter: '/',
|
|
|
|
...(customRoute ? { strict: true } : undefined),
|
|
|
|
decode: decodeParam,
|
|
|
|
})
|
2018-02-01 19:54:09 +01:00
|
|
|
|
2020-01-06 17:43:26 +01:00
|
|
|
return (pathname: string | null | undefined, params?: any) => {
|
2019-11-27 22:48:28 +01:00
|
|
|
const res = pathname == null ? false : matcher(pathname)
|
|
|
|
if (!res) {
|
|
|
|
return false
|
2018-02-01 19:54:09 +01:00
|
|
|
}
|
2019-11-27 22:48:28 +01:00
|
|
|
return { ...params, ...res.params }
|
2018-02-01 19:54:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 16:47:50 +02:00
|
|
|
function decodeParam(param: string) {
|
2018-02-01 19:54:09 +01:00
|
|
|
try {
|
|
|
|
return decodeURIComponent(param)
|
|
|
|
} catch (_) {
|
2018-11-04 01:22:33 +01:00
|
|
|
const err = new Error('failed to decode param')
|
2019-04-24 16:47:50 +02:00
|
|
|
// @ts-ignore DECODE_FAILED is handled
|
2018-11-04 01:22:33 +01:00
|
|
|
err.code = 'DECODE_FAILED'
|
|
|
|
throw err
|
2018-02-01 19:54:09 +01:00
|
|
|
}
|
|
|
|
}
|