8000 Branch was updated using the 'autoupdate branch' Actions workflow. · my-lambda-projects/docs@f6c8b6d · GitHub
[go: up one dir, main page]

Skip to content

Commit f6c8b6d

Browse files
authored
Branch was updated using the 'autoupdate branch' Actions workflow.
2 parents abeee85 + bede852 commit f6c8b6d

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

middleware/detect-language.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff 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)

tests/unit/detect-language.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
})

0 commit comments

Comments
 (0)
0