openapi-alchemist
Version:
Transform OpenAPI 3 to Swagger 2 with alchemical precision
45 lines (44 loc) • 1.71 kB
JavaScript
;
const types_1 = require("./types");
const openapi_3_1 = require("./lib/formats/openapi_3");
const swagger_2_1 = require("./lib/formats/swagger_2");
const Formats = {};
Formats['swagger_2'] = swagger_2_1.Swagger2;
Formats['openapi_3'] = openapi_3_1.OpenApi3;
global.Formats = Formats;
const Converter = {
Formats,
BaseFormat: types_1.BaseFormat,
ResourceReaders: types_1.Util.resourceReaders,
getSpec(source, format, callback) {
if (!Formats.hasOwnProperty(format)) {
throw new Error('Unknown format ' + format + ', you might have forgotten installing an optional dependency');
}
const FormatClass = Formats[format];
const spec = new FormatClass();
const result = spec.resolveResources(source).then(() => spec);
if (callback) {
result.then(result => callback(null, result)).catch(err => callback(err, null));
}
return result;
},
getFormatName(name, version) {
let result;
Object.entries(Formats).forEach(([formatName, format]) => {
const formatPrototype = format.prototype;
if (formatPrototype.formatName === name && formatPrototype.supportedVersions.indexOf(version) !== -1) {
result = formatName;
}
});
return result;
},
convert(options, callback) {
const result = Converter.getSpec(options.source, options.from)
.then((fromSpec) => fromSpec.convertTo(options.to, options.passthrough));
if (callback) {
result.then(result => callback(null, result)).catch(err => callback(err, null));
}
return result;
}
};
module.exports = Converter;