Last active
February 21, 2019 15:45
-
-
Save jslyonnais/3f3921fe9aa05fe8fa41b331c6a120f0 to your computer and use it in GitHub Desktop.
Gatsby & NetlifyCMS concatenate script with multilanguages support
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
const fs = require('fs') | |
const YAML = require('json-to-pretty-yaml') | |
const configPath = '/static/admin' | |
const configs = require('require-all')(__dirname + `${configPath}/config`) | |
const languages = ['fr', 'en'] | |
let obj = { | |
'backend': {}, | |
'collections': [] | |
} | |
const createNewCollectionsType = (category, name) => { | |
obj[category][name] = { | |
'label' : name, | |
'name' : name, | |
'files' : [] | |
} | |
} | |
const replaceDataLang = (data, lang) => { | |
const objString = JSON.stringify(data) | |
const replaceLangVar = objString.replace(/{{lang}}/g, lang) | |
return JSON.parse(replaceLangVar) | |
} | |
const sortCollectionsByName = (a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0) | |
const createUniqueObject = () => { | |
Object.entries(configs).map((file) => { | |
const infos = file[0] | |
const data = file[1] | |
const category = (infos.indexOf('-') > -1) ? infos.split('-')[0] : infos | |
const type = (infos.indexOf('-') > -1) ? infos.split('-')[1] : null | |
const name = (infos.indexOf('-') > -1) ? infos.split('-')[2] : null | |
return languages.map(lang => { | |
if(type && name) { | |
const typeWithLang = `${lang}_${type}` | |
if(!obj[category][typeWithLang]) { | |
createNewCollectionsType(category, typeWithLang) | |
} | |
return obj[category][typeWithLang]['files'].push(replaceDataLang(data, lang)) | |
} else if(type) { | |
return obj[category].push(replaceDataLang(data, lang)) | |
} | |
return obj[category] = replaceDataLang(data, lang) | |
}) | |
}) | |
return constructFinalObject() | |
} | |
const constructFinalObject = () => { | |
var output = { | |
'collections': [] | |
} | |
Object.entries(obj).map((category) => { | |
(category[0] === 'collections') ? | |
Object.entries(category[1]).map((entry) => { | |
const firstObjectInList = entry[1] | |
return output['collections'].push(firstObjectInList) | |
}) | |
: Object.entries(category[1]).map(entry => { | |
let key = entry[0]; | |
let value = entry[1]; | |
return output[key] = value | |
}); | |
}) | |
output['collections'].sort(sortCollectionsByName) | |
saveToFile(output) | |
} | |
const saveToFile = (output) => { | |
const fileName = `.${configPath}/config.yml` | |
fs.writeFile(fileName, YAML.stringify(output), function(err) { | |
if(err) { | |
return console.log(err) | |
} | |
console.log(`⚙️ Config was successfully created!`) | |
}) | |
} | |
// Execute! | |
createUniqueObject() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment