diff --git a/middleware/changeLanguage.js b/middleware/changeLanguage.js index f8f07c8c9..90d45b99e 100644 --- a/middleware/changeLanguage.js +++ b/middleware/changeLanguage.js @@ -1,3 +1,4 @@ +var field = require('../helper/fieldValue'); var logger = require( 'pelias-logger' ).get( 'api' ); const _ = require('lodash'); @@ -64,6 +65,11 @@ function updateDocs( req, res, translations ){ // iterate over response documents res.data.forEach( function( doc, p ){ + // update name.default to the request language (if available) + if (req.clean.lang.defaulted === false) { + translateNameDefault(doc, req.clean.lang.iso6391); + } + // skip invalid records if( !doc || !doc.parent ){ return; } @@ -120,4 +126,11 @@ function isLanguageChangeRequired( req, res ){ req.hasOwnProperty('language'); } +// update name.default with the corresponding translation if available +function translateNameDefault(doc, lang) { + if (lang && _.has(doc, 'name.' + lang)) { + doc.name.default = field.getStringValue(doc.name[lang]); + } +} + module.exports = setup; diff --git a/test/unit/middleware/changeLanguage.js b/test/unit/middleware/changeLanguage.js index ecdb40d0c..66c1fda31 100644 --- a/test/unit/middleware/changeLanguage.js +++ b/test/unit/middleware/changeLanguage.js @@ -133,7 +133,9 @@ module.exports.tests.success_conditions = (test, common) => { const req = { clean: { lang: { - iso6393: 'requested language' + iso6393: 'requested language', + iso6391: 'requested language', + defaulted: false } } }; @@ -179,6 +181,32 @@ module.exports.tests.success_conditions = (test, common) => { layer13_id: [undefined], layer13: ['original name for layer13'] } + }, + // doc with name that will be translated + { + name: { + default: 'original name for 4th result', + 'requested language': 'translated name' + }, + // note that this is address! + layer: 'address', + parent: { + layer1_id: ['1'], + layer1: ['original name for layer1'] + } + }, + // doc with name that will be translated + { + name: { + default: 'original name for 5th result', + 'random language': 'translated name' + }, + // note that this is address! + layer: 'address', + parent: { + layer1_id: ['1'], + layer1: ['original name for layer1'] + } } ] }; @@ -223,6 +251,28 @@ module.exports.tests.success_conditions = (test, common) => { layer13_id: [undefined], layer13: ['original name for layer13'] } + }, + { + name: { + default: 'translated name', + 'requested language': 'translated name' + }, + layer: 'address', + parent: { + layer1_id: ['1'], + layer1: ['replacement name for layer1'] + } + }, + { + name: { + default: 'original name for 5th result', + 'random language': 'translated name' + }, + layer: 'address', + parent: { + layer1_id: ['1'], + layer1: ['replacement name for layer1'] + } } ] });