1- import languages from '#src/languages/lib/languages.js'
2- import { defaultCacheControl } from '#src/frame/middleware/cache-control.js'
1+ import type { NextFunction , Response } from 'express'
2+
3+ import languages from '@/languages/lib/languages.js'
4+ import { defaultCacheControl } from '@/frame/middleware/cache-control.js'
5+ import { ExtendedRequest } from '@/types'
36
47const redirectPatterns = Object . values ( languages )
58 . map ( ( language ) => language . redirectPatterns || [ ] )
@@ -16,14 +19,18 @@ const allRedirectPatterns = Object.values(languages)
1619 . map ( ( language ) =>
1720 ( language . redirectPatterns || [ ] ) . map ( ( redirectPattern ) => [ language . code , redirectPattern ] ) ,
1821 )
19- . flat ( )
22+ . flat ( ) as [ string , RegExp ] [ ] // Seems TypeScript didn't understand the .flat()
2023
2124// This middleware handles redirects for mistyped language codes
2225//
2326// Examples:
2427// /jp* -> /ja*
2528// /zh-TW* -> /zh*
26- export default function languageCodeRedirects ( req , res , next ) {
29+ export default function languageCodeRedirects (
30+ req : ExtendedRequest ,
31+ res : Response ,
32+ next : NextFunction ,
33+ ) {
2734 // Only in the unlikely event that the `req.path` starts with one of these
2835 // prefixes do we bother looking up what the redirect should be.
2936 if ( req . path . startsWith ( '/_next/static' ) ) return next ( )
@@ -32,10 +39,13 @@ export default function languageCodeRedirects(req, res, next) {
3239
3340 // This loop is almost never ever used so it doesn't have to be
3441 // particularly smart or fast.
35- const [ code , pattern ] = allRedirectPatterns . find ( ( [ , pattern ] ) => pattern . test ( req . path ) )
36- if ( code && pattern ) {
37- defaultCacheControl ( res )
38- return res . redirect ( 301 , req . path . replace ( pattern , `/${ code } ` ) )
42+ const matched = allRedirectPatterns . find ( ( [ , pattern ] ) => pattern . test ( req . path ) )
43+ if ( matched ) {
44+ const [ code , pattern ] = matched
45+ if ( code && pattern ) {
46+ defaultCacheControl ( res )
47+ return res . redirect ( 301 , req . path . replace ( pattern , `/${ code } ` ) )
48+ }
3949 }
4050 return next ( )
4151}
0 commit comments