2018-02-01 19:54:09 +01:00
|
|
|
// We borrow this code from https://github.com/pillarjs/path-match
|
|
|
|
// That's because, ^^^ package comes with very old version of path-to-regexp
|
|
|
|
// So, it'll give us issues when the app has used a newer version of path-to-regexp
|
|
|
|
// (When webpack resolving packages)
|
2019-04-24 16:47:50 +02:00
|
|
|
const pathToRegexp = require('path-to-regexp')
|
2018-02-01 19:54:09 +01:00
|
|
|
|
2019-04-24 16:47:50 +02:00
|
|
|
export default () => {
|
|
|
|
return (path: string) => {
|
|
|
|
const keys: any[] = []
|
|
|
|
const re = pathToRegexp(path, keys, {})
|
2018-02-01 19:54:09 +01:00
|
|
|
|
2019-04-24 16:47:50 +02:00
|
|
|
return (pathname: string|undefined, params?: any) => {
|
|
|
|
const m = re.exec(pathname)
|
2018-02-01 19:54:09 +01:00
|
|
|
if (!m) return false
|
|
|
|
|
|
|
|
params = params || {}
|
|
|
|
|
2019-04-24 16:47:50 +02:00
|
|
|
let key
|
|
|
|
let param
|
|
|
|
for (let i = 0; i < keys.length; i++) {
|
2018-02-01 19:54:09 +01:00
|
|
|
key = keys[i]
|
|
|
|
param = m[i + 1]
|
|
|
|
if (!param) continue
|
|
|
|
params[key.name] = decodeParam(param)
|
|
|
|
if (key.repeat) params[key.name] = params[key.name].split(key.delimiter)
|
|
|
|
}
|
|
|
|
|
|
|
|
return params
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|