1
- const pathMatch = require ( 'path-match' ) ( )
1
+ import pathMatch from 'path-match'
2
+ const path = pathMatch ( )
2
3
3
4
/**
4
5
*
5
6
* @param {object } options
6
7
* @param {import('next').Server } nextApp
7
8
* @returns {import('express').Handler[] }
8
9
*/
9
- function createMiddleware ( { locales, defaultLocale, subPaths, ignoreRoutes } ) {
10
+ export function createMiddleware ( { locales, defaultLocale, subPaths, ignoreRoutes } ) {
10
11
const localesWithoutDefault = ( ) => locales . filter ( lang => lang !== defaultLocale )
11
- const getPathWithTrallingSlash = ( path ) => localesWithoutDefault ( ) . some ( lng => path === `/${ lng } ` ) ? `${ path } /` : path
12
+ const getPathWithTrallingSlash = path =>
13
+ localesWithoutDefault ( ) . some ( lng => path === `/${ lng } ` ) ? `${ path } /` : path
12
14
const ignoreRegex = new RegExp ( `^/(?!${ ignoreRoutes . map ( x => x . replace ( '/' , '' ) ) . join ( '|' ) } ).*$` )
13
- const ignoreRoute = pathMatch ( ignoreRegex )
15
+ const ignoreRoute = path ( ignoreRegex )
14
16
const isI18nRoute = req => ignoreRoute ( req . url ) && req . method === 'GET'
15
- const routeWithLang = pathMatch ( `/:lang(${ localesWithoutDefault ( )
16
- . join ( '|' ) } )?/*`)
17
+ const routeWithLang = path ( `/:lang(${ localesWithoutDefault ( ) . join ( '|' ) } )?/*` )
17
18
const parseRoute = pathname => routeWithLang ( pathname )
18
19
/**
19
20
* @type {import('express').Handler[] }
@@ -34,28 +35,34 @@ function createMiddleware ({ locales, defaultLocale, subPaths, ignoreRoutes }) {
34
35
if ( subPaths ) {
35
36
middlewares . push ( ( req , res , next ) => {
36
37
if ( ! isI18nRoute ( req ) ) return next ( )
38
+ const savedPath = req . path
37
39
const pathname = getPathWithTrallingSlash ( req . path )
38
40
const { lang, 0 : otherPath } = parseRoute ( pathname )
39
- const { lingui : { locale : userLocale } } = req
41
+ const {
42
+ lingui : { locale : userLocale } ,
43
+ } = req
40
44
req . url = otherPath ? `/${ otherPath } ` : '/'
41
45
42
46
if ( userLocale === defaultLocale && lang == null ) {
43
47
return next ( )
44
48
}
45
49
46
- if ( userLocale === lang ) {
47
- return next ( )
48
- }
49
-
50
50
if ( userLocale === defaultLocale && lang != null ) {
51
51
return res . redirect ( `/${ otherPath } ` )
52
52
}
53
53
54
+ if ( userLocale === lang && ! otherPath && ! / \/ $ / . test ( savedPath ) ) {
55
+ return res . redirect ( pathname )
56
+ }
57
+
58
+ if ( userLocale === lang ) {
59
+ return next ( )
60
+ }
61
+
62
+ console . log ( userLocale , otherPath )
54
63
return res . redirect ( `/${ userLocale } ${ otherPath ? `/${ otherPath } ` : '' } ` )
55
64
} )
56
65
}
57
66
58
67
return middlewares
59
68
}
60
-
61
- module . exports = createMiddleware
0 commit comments