rsnext/packages/next/shared/lib/i18n/detect-domain-locale.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

30 lines
760 B
TypeScript

import type { DomainLocale } from '../../../server/config-shared'
export function detectDomainLocale(
domainItems?: DomainLocale[],
hostname?: string,
detectedLocale?: string
) {
let domainItem: DomainLocale | undefined
if (domainItems) {
if (detectedLocale) {
detectedLocale = detectedLocale.toLowerCase()
}
for (const item of domainItems) {
// remove port if present
const domainHostname = item.domain?.split(':')[0].toLowerCase()
if (
hostname === domainHostname ||
detectedLocale === item.defaultLocale.toLowerCase() ||
item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)
) {
domainItem = item
break
}
}
}
return domainItem
}