openapi-modifier
Version:
This package allows you to automate the process of modifying OpenAPI specifications by applying a set of predefined rules
50 lines (49 loc) • 1.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryExtractRefLastPath = exports.resolveRef = exports.checkIsRefSchema = void 0;
const checkIsRefSchema = (schema) => {
return !!schema && typeof schema === 'object' && '$ref' in schema;
};
exports.checkIsRefSchema = checkIsRefSchema;
// TODO improve types
const get = (obj, path) => {
const fullPath = path.split(".");
try {
const result = fullPath.reduce((acc, pathPart) => {
// @ts-expect-error
return acc[pathPart];
}, obj);
return result;
}
catch (error) {
return undefined;
}
};
const preparedRef = (ref) => {
return ref.replace('#/', '').replace(/\//g, '.');
};
const resolveRef = (openAPIFile, referenceObject) => {
let ref = referenceObject.$ref;
const isLocalRef = ref.startsWith('#/');
if (!isLocalRef) {
throw new Error('Not support resolve not local ref!');
}
ref = preparedRef(ref);
const result = get(openAPIFile.document, ref);
const isRefResult = (0, exports.checkIsRefSchema)(result);
if (isRefResult) {
return (0, exports.resolveRef)(openAPIFile, result);
}
return result;
};
exports.resolveRef = resolveRef;
const tryExtractRefLastPath = (ref) => {
try {
const paths = ref.split('/');
return paths[paths.length - 1] || null;
}
catch (error) {
return null;
}
};
exports.tryExtractRefLastPath = tryExtractRefLastPath;