Skip to content

Commit

Permalink
fix: detect-language correctly handles root path, add unit tests (git…
Browse files Browse the repository at this point in the history
  • Loading branch information
mikesurowiec authored Oct 26, 2021
1 parent 6112336 commit bede852
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
15 changes: 7 additions & 8 deletions middleware/detect-language.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,14 @@ function getUserLanguage(browserLanguages) {
}
}

export default function detectLanguage(req, res, next) {
// determine language code from the URL, or default to English
// /en/articles/foo
// ^^
// /_next/data/development/en/articles/foo
// ^^
const maybeLanguage = req.path.split('/')[req.path.startsWith('/_next/data/') ? 4 : 1]
// determine language code from a path. Default to en if no valid match
export function getLanguageCodeFromPath(path) {
const maybeLanguage = path.split('/')[path.startsWith('/_next/data/') ? 4 : 1].slice(0, 2)
return languageCodes.includes(maybeLanguage) ? maybeLanguage : 'en'
}

req.language = languageCodes.includes(maybeLanguage) ? maybeLanguage : 'en'
export default function detectLanguage(req, res, next) {
req.language = getLanguageCodeFromPath(req.path)
// Detecting browser language by user preference
const browserLanguages = parser.parse(req.headers['accept-language'])
req.userLanguage = getUserLanguage(browserLanguages)
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/detect-language.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { expect } from '@jest/globals'
import { getLanguageCodeFromPath } from '../../middleware/detect-language.js'

describe('detect-language - getLanguageCodeFromPath', () => {
test('should handle client-side routing path shape', () => {
expect(getLanguageCodeFromPath('/_next/data/development/ja/articles/foo')).toBe('ja')
})

test('should return for paths with an extension', () => {
expect(getLanguageCodeFromPath('/ja.json')).toBe('ja')
expect(getLanguageCodeFromPath('/_next/data/development/ja.json')).toBe('ja')
})

test('should return en for invalid languages', () => {
expect(getLanguageCodeFromPath('/xx/articles/foo')).toBe('en')
expect(getLanguageCodeFromPath('/_next/data/development/xx/articles/foo')).toBe('en')
})
})

0 comments on commit bede852

Please sign in to comment.