@bitblit/ratchet-epsilon-common
Version:
Tiny adapter to simplify building API gateway Lambda APIS
80 lines • 3.51 kB
JavaScript
import yaml from 'js-yaml';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
export class OpenApiDocModifier {
options;
constructor(options) {
this.options = options;
}
modifyOpenApiDoc(yamlString) {
let rval;
if (!!yamlString && !!this.options) {
try {
const openApi = yaml.load(yamlString);
const removeTags = this.options.removeTags ? this.options.removeTags.map((t) => t.toLowerCase()) : [];
if (this.options.newServerPath) {
openApi['servers'] = [{ url: this.options.newServerPath }];
}
if (!!this.options.removeTags && openApi['tags']) {
if (openApi['tags']) {
openApi['tags'] = openApi.tags.filter((f) => {
const n = !!f && !!f['name'] ? f['name'].toLowerCase() : '';
const i = removeTags.indexOf(n);
return i === -1;
});
}
}
if (openApi['paths']) {
let newPaths = {};
Object.keys(openApi['paths']).forEach((p) => {
const path = openApi['paths'][p];
Object.keys(path).forEach((verb) => {
const entry = path[verb];
entry.tags = entry.tags ? entry.tags.filter((t) => removeTags.lastIndexOf(t.toLowerCase()) == -1) : entry.tags;
const matcher = verb.toLowerCase() + ' ' + p.toLowerCase();
if (this.matchNone(matcher, this.options.removeEndpoints)) {
newPaths[p] = newPaths[p] || {};
newPaths[p][verb] = entry;
}
});
});
if (this.options.sortEndpoints) {
const keys = Object.keys(newPaths).sort();
const newPaths2 = {};
keys.forEach((k) => {
newPaths2[k] = newPaths[k];
});
newPaths = newPaths2;
}
openApi['paths'] = newPaths;
}
let remSchemas = this.options.removeSchemas || [];
remSchemas = remSchemas.map((s) => s.toLowerCase());
if (openApi['components'] && openApi['components']['schemas']) {
const keys = Object.keys(openApi['components']['schemas']).sort();
const newComp = {};
keys.forEach((k) => {
if (remSchemas.indexOf(k.toLowerCase()) === -1) {
newComp[k] = openApi['components']['schemas'][k];
}
});
openApi['components']['schemas'] = newComp;
}
rval = yaml.dump(openApi);
}
catch (err) {
Logger.error('Error processing yaml: %s', err, err);
}
}
return rval;
}
matchNone(input, regex) {
let rval = true;
if (!!input && !!regex) {
regex.forEach((r) => {
rval = rval && !r.test(input);
});
}
return rval;
}
}
//# sourceMappingURL=open-api-doc-modifier.js.map