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

32 lines
752 B
TypeScript
Raw Normal View History

import { match } from 'path-to-regexp'
2019-11-09 23:34:53 +01:00
export default (customRoute = false) => {
return (path: string) => {
const matcher = match(path, {
sensitive: false,
delimiter: '/',
...(customRoute ? { strict: true } : undefined),
decode: decodeParam,
})
return (pathname: string | undefined, params?: any) => {
const res = pathname == null ? false : matcher(pathname)
if (!res) {
return false
}
return { ...params, ...res.params }
}
}
}
function decodeParam(param: string) {
try {
return decodeURIComponent(param)
} catch (_) {
const err = new Error('failed to decode param')
// @ts-ignore DECODE_FAILED is handled
err.code = 'DECODE_FAILED'
throw err
}
}