Last active
March 11, 2019 06:50
-
-
Save dabernathy89/0d33a81ef004e8d8d4ed702ee39a9d9d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { join } = require('path'); | |
const _ = require('lodash'); | |
function getAllDirectoriesNested(path, allDirectories) { | |
allDirectories = allDirectories || []; | |
let directories = fs.readdirSync(path) | |
.filter(file => { | |
return fs.statSync(join(path, file)).isDirectory(); | |
}) | |
.map(file => join(path, file)); | |
directories.forEach(directory => { | |
allDirectories.push(directory); | |
getAllDirectoriesNested('./' + directory + '/', allDirectories); | |
}); | |
return allDirectories; | |
} | |
function getAllFiles(path) { | |
return fs.readdirSync(path).filter(file => { | |
return fs.statSync(join(path, file)).isFile() | |
&& !['package.json', 'package-lock.json'].includes(file) | |
&& file.substr(file.length - 5) === '.json'; | |
}); | |
} | |
function process(path, obj, isInitial) { | |
obj = obj || {}; | |
isInitial = isInitial || false; | |
// For the Open API `paths` object, we want to be able to organize the folders in a nested structure, but insert | |
// the paths back into the object in a single property per path (e.g., "users/{userId}") | |
let directories = []; | |
if (path.substr(path.length - 6) === 'paths/') { | |
directories = getAllDirectoriesNested(path).map(directory => directory.replace('paths/', '')); | |
} else if (path.indexOf('paths/') === -1) { | |
directories = fs.readdirSync(path).filter(file => { | |
return fs.statSync(join(path, file)).isDirectory() && !['node_modules', 'dist'].includes(file); | |
}); | |
} | |
let files = isInitial ? [] : getAllFiles(path); | |
files.forEach(file => { | |
let json_contents = JSON.parse(fs.readFileSync(path + file)); | |
obj[file.substr(0, file.length - 5)] = json_contents; | |
}); | |
directories.forEach(directory => { | |
let prefix = (path === './paths/') ? '/' : ''; | |
let result = process(path + directory + '/'); | |
if (!_.isEmpty(result)) { | |
obj[prefix + directory] = result; | |
} | |
}); | |
return obj; | |
} | |
let openapiJson = JSON.parse(fs.readFileSync('./openapi.json')); | |
openapiJson = process('./', openapiJson, true); | |
fs.writeFile('./dist/openapi.json', JSON.stringify(openapiJson), () => { | |
console.log('Open API file generated!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment