File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -34,15 +34,14 @@ function getUserLanguage(browserLanguages) {
3434 }
3535}
3636
37- export default function detectLanguage ( req , res , next ) {
38- // determine language code from the URL, or default to English
39- // /en/articles/foo
40- // ^^
41- // /_next/data/development/en/articles/foo
42- // ^^
43- const maybeLanguage = req . path . split ( '/' ) [ req . path . startsWith ( '/_next/data/' ) ? 4 : 1 ]
37+ // determine language code from a path. Default to en if no valid match
38+ export function getLanguageCodeFromPath ( path ) {
39+ const maybeLanguage = path . split ( '/' ) [ path . startsWith ( '/_next/data/' ) ? 4 : 1 ] . slice ( 0 , 2 )
40+ return languageCodes . includes ( maybeLanguage ) ? maybeLanguage : 'en'
41+ }
4442
45- req . language = languageCodes . includes ( maybeLanguage ) ? maybeLanguage : 'en'
43+ export default function detectLanguage ( req , res , next ) {
44+ req . language = getLanguageCodeFromPath ( req . path )
4645 // Detecting browser language by user preference
4746 const browserLanguages = parser . parse ( req . headers [ 'accept-language' ] )
4847 req . userLanguage = getUserLanguage ( browserLanguages )
Original file line number Diff line number Diff line change 1+ import { expect } from '@jest/globals'
2+ import { getLanguageCodeFromPath } from '../../middleware/detect-language.js'
3+
4+ describe ( 'detect-language - getLanguageCodeFromPath' , ( ) => {
5+ test ( 'should handle client-side routing path shape' , ( ) => {
6+ expect ( getLanguageCodeFromPath ( '/_next/data/development/ja/articles/foo' ) ) . toBe ( 'ja' )
7+ } )
8+
9+ test ( 'should return for paths with an extension' , ( ) => {
10+ expect ( getLanguageCodeFromPath ( '/ja.json' ) ) . toBe ( 'ja' )
11+ expect ( getLanguageCodeFromPath ( '/_next/data/development/ja.json' ) ) . toBe ( 'ja' )
12+ } )
13+
14+ test ( 'should return en for invalid languages' , ( ) => {
15+ expect ( getLanguageCodeFromPath ( '/xx/articles/foo' ) ) . toBe ( 'en' )
16+ expect ( getLanguageCodeFromPath ( '/_next/data/development/xx/articles/foo' ) ) . toBe ( 'en' )
17+ } )
18+ } )
You can’t perform that action at this time.
0 commit comments