Skip to content

Instantly share code, notes, and snippets.

@dabernathy89
Last active March 11, 2019 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabernathy89/0d33a81ef004e8d8d4ed702ee39a9d9d to your computer and use it in GitHub Desktop.
Save dabernathy89/0d33a81ef004e8d8d4ed702ee39a9d9d to your computer and use it in GitHub Desktop.
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