@opendoc/openapi-shaking
Version:
Remove the useless components and paths of openapi document.
34 lines (33 loc) • 1.42 kB
JavaScript
import * as R from 'ramda';
import { OpenapiReferenceParser } from '@opendoc/openapi-reference-parser';
export function openapiShakingOrphanedComponents(document) {
const dependencies = new OpenapiReferenceParser(document).parse();
const refs = R.unnest(Object.values(dependencies.paths || {})
.map((pathObj) => R.unnest(Object.values(pathObj || {})
.map((op) => op.dependencies))));
const exists = refs
.map((ref) => ref.match(/#\/components\/(.+?)\/(.+)/))
.filter((matched) => !!matched)
.map((matched) => ({
scopeName: matched[1],
componentName: matched[2],
}));
const isExist = (scopeName, componentName) => exists.some((item) => item.scopeName === scopeName &&
item.componentName === componentName);
let doc = document;
for (const scopeName in document.components) {
if (!document.components[scopeName])
continue;
for (const componentName in document.components[scopeName]) {
if (!document.components[scopeName][componentName])
continue;
if (!isExist(scopeName, componentName)) {
doc = R.dissocPath(['components', scopeName, componentName], doc);
}
}
if (R.isEmpty(R.path(['components', scopeName], doc))) {
doc = R.dissocPath(['components', scopeName], doc);
}
}
return doc;
}