2020-03-29 19:17:06 +02:00
|
|
|
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
|
2019-12-23 22:20:17 +01:00
|
|
|
|
|
|
|
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) => {
|
2020-01-16 23:38:38 +01:00
|
|
|
const keys: pathToRegexp.Key[] = []
|
|
|
|
const matcherOptions = {
|
2019-11-27 22:48:28 +01:00
|
|
|
sensitive: false,
|
|
|
|
delimiter: '/',
|
|
|
|
...(customRoute ? { strict: true } : undefined),
|
|
|
|
decode: decodeParam,
|
2020-01-16 23:38:38 +01:00
|
|
|
}
|
|
|
|
const matcherRegex = pathToRegexp.pathToRegexp(path, keys, matcherOptions)
|
|
|
|
const matcher = pathToRegexp.regexpToFunction(
|
|
|
|
matcherRegex,
|
|
|
|
keys,
|
|
|
|
matcherOptions
|
|
|
|
)
|
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
|
|
|
}
|
2020-01-16 23:38:38 +01:00
|
|
|
|
|
|
|
if (customRoute) {
|
|
|
|
for (const key of keys) {
|
2020-03-10 21:09:35 +01:00
|
|
|
// unnamed params should be removed as they
|
|
|
|
// are not allowed to be used in the destination
|
2020-01-16 23:38:38 +01:00
|
|
|
if (typeof key.name === 'number') {
|
2020-03-10 21:09:35 +01:00
|
|
|
delete (res.params as any)[key.name]
|
2020-01-16 23:38:38 +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 (_) {
|
2020-02-17 22:16:19 +01:00
|
|
|
const err: Error & { code?: string } = new Error('failed to decode param')
|
2018-11-04 01:22:33 +01:00
|
|
|
err.code = 'DECODE_FAILED'
|
|
|
|
throw err
|
2018-02-01 19:54:09 +01:00
|
|
|
}
|
|
|
|
}
|