2021-07-05 18:31:32 +02:00
|
|
|
import { DecodeError } from '../../utils'
|
2019-05-30 22:42:45 +02:00
|
|
|
import { getRouteRegex } from './route-regex'
|
|
|
|
|
|
|
|
export function getRouteMatcher(routeRegex: ReturnType<typeof getRouteRegex>) {
|
|
|
|
const { re, groups } = routeRegex
|
2020-01-06 17:43:26 +01:00
|
|
|
return (pathname: string | null | undefined) => {
|
2019-05-30 22:42:45 +02:00
|
|
|
const routeMatch = re.exec(pathname!)
|
|
|
|
if (!routeMatch) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-04-02 09:24:32 +02:00
|
|
|
const decode = (param: string) => {
|
|
|
|
try {
|
|
|
|
return decodeURIComponent(param)
|
|
|
|
} catch (_) {
|
2021-07-05 18:31:32 +02:00
|
|
|
throw new DecodeError('failed to decode param')
|
2020-04-02 09:24:32 +02:00
|
|
|
}
|
|
|
|
}
|
2019-11-15 08:19:41 +01:00
|
|
|
const params: { [paramName: string]: string | string[] } = {}
|
2019-05-30 22:42:45 +02:00
|
|
|
|
|
|
|
Object.keys(groups).forEach((slugName: string) => {
|
2019-12-02 22:55:49 +01:00
|
|
|
const g = groups[slugName]
|
|
|
|
const m = routeMatch[g.pos]
|
2019-05-30 22:42:45 +02:00
|
|
|
if (m !== undefined) {
|
2019-12-02 22:55:49 +01:00
|
|
|
params[slugName] = ~m.indexOf('/')
|
2020-05-18 21:24:37 +02:00
|
|
|
? m.split('/').map((entry) => decode(entry))
|
2019-12-02 22:55:49 +01:00
|
|
|
: g.repeat
|
|
|
|
? [decode(m)]
|
|
|
|
: decode(m)
|
2019-05-30 22:42:45 +02:00
|
|
|
}
|
|
|
|
})
|
|
|
|
return params
|
|
|
|
}
|
|
|
|
}
|