rsnext/packages/next/next-server/lib/router/utils/path-match.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-03-29 19:17:06 +02:00
import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
export { pathToRegexp }
export const matcherOptions: pathToRegexp.TokensToRegexpOptions &
pathToRegexp.ParseOptions = {
sensitive: false,
delimiter: '/',
}
export const customRouteMatcherOptions: pathToRegexp.TokensToRegexpOptions &
pathToRegexp.ParseOptions = {
...matcherOptions,
strict: true,
}
2019-11-09 23:34:53 +01:00
export default (customRoute = false) => {
return (path: string) => {
const keys: pathToRegexp.Key[] = []
const matcherRegex = pathToRegexp.pathToRegexp(
path,
keys,
customRoute ? customRouteMatcherOptions : matcherOptions
)
const matcher = pathToRegexp.regexpToFunction(matcherRegex, keys)
2020-01-06 17:43:26 +01:00
return (pathname: string | null | undefined, params?: any) => {
const res = pathname == null ? false : matcher(pathname)
if (!res) {
return false
}
if (customRoute) {
for (const key of keys) {
// unnamed params should be removed as they
// are not allowed to be used in the destination
if (typeof key.name === 'number') {
delete (res.params as any)[key.name]
}
}
}
return { ...params, ...res.params }
}
}
}