rsnext/packages/next/shared/lib/router/utils/parse-url.ts
Javi Velasco e65c56e7e6
Refactor i18n checks on request handling (#27328)
Currently there is a lot of mutation in the Next.js Server and the checks for Locale are directly coded in the general request handler. Ideally, we should have a function where we just pass the request input (url + headers + config) and generate a bunch of metadata that analyzes it generating all metadata we might require for both the URL and i18n + basePath information.

This PR brings:
- A new parsing function `parseUrl` that joins parsing an absolute/relative URL into a data structure compatible with the Node parsing output but missing redundant properties.
- A wrapper `parseNextURL` that extends `parseUrl` analyzing `i18n` and `basePath` based on the provided configuration, url and headers. This function is pure and stateless so it can be used outside of the Next.js context.
- Types improvements and reuse.
- Refactors `next-server.ts` request handling using the above mentioned functions so that the code there just apply effects to the `req` object and the `parsedUrl.query` leaving the code much more straightforward.
- Refactors `getRouteRegex` decomposing in two different functions where `getParametrizedRoute` can be used to retrieve the serializable data that is used to generate the Regex.
2021-07-21 16:12:33 +00:00

32 lines
798 B
TypeScript

import type { ParsedUrlQuery } from 'querystring'
import { searchParamsToUrlQuery } from './querystring'
import { parseRelativeUrl } from './parse-relative-url'
export interface ParsedUrl {
hash: string
hostname?: string | null
href: string
pathname: string
port?: string | null
protocol?: string | null
query: ParsedUrlQuery
search: string
}
export function parseUrl(url: string): ParsedUrl {
if (url.startsWith('/')) {
return parseRelativeUrl(url)
}
const parsedURL = new URL(url)
return {
hash: parsedURL.hash,
hostname: parsedURL.hostname,
href: parsedURL.href,
pathname: parsedURL.pathname,
port: parsedURL.port,
protocol: parsedURL.protocol,
query: searchParamsToUrlQuery(parsedURL.searchParams),
search: parsedURL.search,
}
}