Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active July 10, 2024 14:12
Show Gist options
  • Save mholtzhausen/425ce4d8e6f0504bb9e029b91dacb9a1 to your computer and use it in GitHub Desktop.
Save mholtzhausen/425ce4d8e6f0504bb9e029b91dacb9a1 to your computer and use it in GitHub Desktop.
Load a Yaml file, and resolve $ref references
import fs from 'fs'
import path from 'path'
import YAML from 'js-yaml'
/**
* Process an object with references
* @param {object} obj - the object to process
* @param {string} rootFolder - the folder where the yaml file is located
* @returns {object}
*/
function processObject(obj, rootFolder) {
for (const prop in obj) {
if (prop === '$ref') {
obj = loadYamlWithRefs(obj[prop], rootFolder)
}
if (typeof obj[prop] === 'object' && obj[prop].$ref) {
obj[prop] = loadYamlWithRefs(obj[prop].$ref, rootFolder)
} else if (Array.isArray(obj[prop])) {
let arr = obj[prop].reduce((acc, item) => {
if (typeof item === 'object' && item.$ref) {
let incoming = loadYamlWithRefs(item.$ref, rootFolder)
if (Array.isArray(incoming)) acc = acc.concat(incoming)
else acc.push(incoming)
} else {
acc.push(item)
}
return acc
}, [])
obj[prop] = arr
}
if (typeof obj[prop] === 'object') {
obj[prop] = processObject(obj[prop], rootFolder)
}
}
return obj
}
/**
* Load a yaml file with references
* @param {string} file - the file to load
* @param {string} rootFolder - the folder where the yaml file is located (optional)
* @returns {object}
*
*/
export default function loadYamlWithRefs(file, rootFolder = undefined) {
let filename = file
if (!rootFolder) {
rootFolder = path.dirname(file)
filename = path.basename(file)
}
const yamlFile = path.join(rootFolder, filename)
let doc = YAML.load(fs.readFileSync(yamlFile), { filename: yamlFile })
doc = processObject(doc, rootFolder)
return doc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment