Last active
June 8, 2022 09:58
-
-
Save MarcHagen/ae0e30585b4ae74795c57c9856a9e032 to your computer and use it in GitHub Desktop.
lang_option directus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default ({ init }) => { | |
// traverse the object recursively and filter all translation fields with the given translationFieldName by the specified language | |
function filterTranslations(obj, languageCode, translationFieldName) { | |
if(obj) Object.keys(obj).forEach(key => { | |
if(key === translationFieldName && Array.isArray(obj[key])) { | |
obj[key] = obj[key].find(t => !t.languages_code || t.languages_code.indexOf(languageCode) >= 0); | |
} | |
if (typeof obj[key] === 'object') { | |
obj[key] = filterTranslations(obj[key], languageCode, translationFieldName) | |
} | |
}); | |
return obj; | |
} | |
init('middlewares.after', async ({ app }) => { | |
app.use(function(req, res, next) { | |
// just process if lang query parameter is found | |
// these query params will work: | |
// &lang=de | |
// &lang[content]=de (if you named your translation field other than 'translations') | |
if(!req.query || !req.query.lang) { | |
return next() | |
} | |
// process body only if it's JSON | |
const send = res.send | |
res.send = function(body) { | |
var contentType = res.get('Content-Type') | |
if(contentType && contentType.includes('application/json') && body) { | |
let bodyJSON = JSON.parse(body) | |
// extract language and translation field | |
let translationField = 'translations' | |
let languageCode = req.query.lang | |
if(typeof languageCode === 'object') { | |
translationField = Object.keys(req.query.lang)[0] | |
languageCode = req.query.lang.content | |
} | |
// filter translations | |
if(typeof bodyJSON.data === 'object') { | |
bodyJSON = filterTranslations(bodyJSON, languageCode, translationField) | |
body = JSON.stringify(bodyJSON) | |
} | |
} | |
send.apply(this, [body]) | |
} | |
next() | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment