Headless: Improve createI18nMiddleware function

This commit is contained in:
SonMooSans
2024-01-04 21:14:28 +08:00
parent a47b7b6b21
commit 4c1334e70d
3 changed files with 62 additions and 21 deletions
+24
View File
@@ -0,0 +1,24 @@
---
'next-docs-zeta': major
---
**Improve `createI18nMiddleware` function**
Now, you can export the middleware directly without a wrapper.
From:
```ts
export default function middleware(request: NextRequest) {
return createI18nMiddleware(...);
}
```
To:
```ts
export default createI18nMiddleware({
defaultLanguage,
languages,
})
```
+1
View File
@@ -5,5 +5,6 @@ import { loader } from 'next-docs-zeta/source';
export const { getPage, getPages, pageTree } = loader({
baseUrl: '/docs',
rootDir: 'docs',
languages,
source: createMDXSource(map),
});
+37 -21
View File
@@ -1,9 +1,15 @@
import { match as matchLocale } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
import type { NextMiddlewareResult } from 'next/dist/server/web/types';
import type { NextMiddleware } from 'next/dist/server/web/types';
import type { NextRequest } from 'next/server';
import nextLib from 'next/server';
interface MiddlewareOptions {
languages: string[];
defaultLanguage: string;
format?: (locale: string, path: string) => string;
}
function getLocale(
request: NextRequest,
locales: string[],
@@ -21,29 +27,39 @@ function getLocale(
return matchLocale(languages, locales, defaultLanguage);
}
export function createI18nMiddleware(
request: NextRequest,
languages: string[],
defaultLanguage: string,
format: (locale: string, slug: string) => string,
): NextMiddlewareResult | Promise<NextMiddlewareResult> {
const { pathname } = request.nextUrl;
const defaultFormat: NonNullable<MiddlewareOptions['format']> = (
locale,
path,
) => {
return `/${locale}/${path}`;
};
const pathnameIsMissingLocale = languages.every(
(locale) =>
!pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
);
export function createI18nMiddleware({
languages,
defaultLanguage,
format = defaultFormat,
}: MiddlewareOptions): NextMiddleware {
return (request) => {
const { pathname } = request.nextUrl;
if (pathnameIsMissingLocale) {
const locale = getLocale(request, languages, defaultLanguage);
let path = pathname;
const pathnameIsMissingLocale = languages.every(
(locale) =>
!pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
);
while (path.startsWith('/')) {
path = path.slice(1);
if (pathnameIsMissingLocale) {
const locale = getLocale(request, languages, defaultLanguage);
let path = pathname;
while (path.startsWith('/')) {
path = path.slice(1);
}
return nextLib.NextResponse.redirect(
new URL(format(locale, path), request.url),
);
}
return nextLib.NextResponse.redirect(
new URL(format(locale, path), request.url),
);
}
return nextLib.NextResponse.next();
};
}