From af7d7a91ea2414bf133a690c938d6c421899aef5 Mon Sep 17 00:00:00 2001 From: Orlando Del Aguila Date: Mon, 9 Oct 2023 21:04:48 -0600 Subject: [PATCH] fix(languageDetector): handle numeric special cases --- lib/languageLookups/header.js | 4 +-- test/languageDetector.js | 48 +++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/lib/languageLookups/header.js b/lib/languageLookups/header.js index 525bbd8..3a997c1 100644 --- a/lib/languageLookups/header.js +++ b/lib/languageLookups/header.js @@ -1,4 +1,4 @@ -const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'] +const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab', '419'] export default { name: 'header', @@ -17,7 +17,7 @@ export default { let lookupRegex = /(([a-z]{2,3})-?([A-Z]{2})?)\s*;?\s*(q=([0-9.]+))?/gi if (acceptLanguage.indexOf('-') > 0) { const foundSpecialCase = specialCases.find((s) => acceptLanguage.toLowerCase().indexOf(`-${s}`) > 0) - if (foundSpecialCase) lookupRegex = /(([a-z]{2,3})-?([A-Z]{4})?)\s*;?\s*(q=([0-9.]+))?/gi + if (foundSpecialCase) lookupRegex = /(([a-z]{2,3})-?([A-Z0-9]{2,4})?)\s*;?\s*(q=([0-9.]+))?/gi } const lngs = []; let i; let m const rgx = options.lookupHeaderRegex || lookupRegex diff --git a/test/languageDetector.js b/test/languageDetector.js index 2ccb1c7..86a2c44 100644 --- a/test/languageDetector.js +++ b/test/languageDetector.js @@ -99,6 +99,54 @@ describe('language detector', () => { expect(lng).to.eql('Hans') // expect(res).to.eql({}) }) + + it('detect region with numbers', () => { + const req = { + headers: { + 'accept-language': 'es-419' + } + } + const res = {} + const lng = ld.detect(req, res) + expect(lng).to.eql('es-419') + // expect(res).to.eql({}) + }) + + it('parses weight correctly', () => { + const req = { + headers: { + 'accept-language': 'pt;q=0.9,es-419;q=0.8,en;q=0.7' + } + } + const res = {} + const lng = ld.detect(req, res) + expect(lng).to.eql('pt') + // expect(res).to.eql({}) + }) + + it('parses weight out of order correctly', () => { + const req = { + headers: { + 'accept-language': 'es-419;q=0.7,en;q=0.8,pt;q=0.9' + } + } + const res = {} + const lng = ld.detect(req, res) + expect(lng).to.eql('pt') + // expect(res).to.eql({}) + }) + + it('sets weight to 1 as default', () => { + const req = { + headers: { + 'accept-language': 'pt-BR,pt;q=0.9,es-419;q=0.8,en;q=0.7' + } + } + const res = {} + const lng = ld.detect(req, res) + expect(lng).to.eql('pt-BR') + // expect(res).to.eql({}) + }) }) describe('path', () => {