UNPKG

@opendoc/openapi-shaking

Version:

Remove the useless components and paths of openapi document.

48 lines (47 loc) 2.19 kB
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "ramda", "@opendoc/openapi-reference-parser"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.openapiShakingOrphanedComponents = void 0; const R = require("ramda"); const openapi_reference_parser_1 = require("@opendoc/openapi-reference-parser"); function openapiShakingOrphanedComponents(document) { const dependencies = new openapi_reference_parser_1.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; } exports.openapiShakingOrphanedComponents = openapiShakingOrphanedComponents; });