UNPKG

openapi-modifier

Version:

This package allows you to automate the process of modifying OpenAPI specifications by applying a set of predefined rules

65 lines (64 loc) 2.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setObjectProp = exports.getObjectPath = exports.getPathKeys = void 0; const factory_1 = require("../../../logger/messages/factory"); const getPathKeys = (path) => { if (!path) { return []; } const rawPathKeys = Array.isArray(path) ? path : path.split(/[.\[\]]/); return rawPathKeys.filter(key => !!key); }; exports.getPathKeys = getPathKeys; const normalizePathForLogging = (path) => { if (!path) { return ''; } return Array.isArray(path) ? path.join('.') : path; }; const getObjectPath = (sourceObject, path, sourcePath = path) => { const pathKeys = (0, exports.getPathKeys)(path); if (!(pathKeys === null || pathKeys === void 0 ? void 0 : pathKeys.length)) { throw new Error('Not valid path'); } // @ts-expect-error let resultObject = sourceObject[pathKeys[0]]; if (resultObject === undefined) { if (sourceObject && typeof sourceObject === 'object' && '$ref' in sourceObject) { throw new Error(factory_1.messagesFactory.failedToResolvePath.conflictRef(normalizePathForLogging(sourcePath), sourceObject, normalizePathForLogging(path))); } if (sourceObject && typeof sourceObject === 'object' && 'allOf' in sourceObject) { throw new Error(factory_1.messagesFactory.failedToResolvePath.conflictAllOf(normalizePathForLogging(sourcePath), sourceObject, normalizePathForLogging(path))); } if (sourceObject && typeof sourceObject === 'object' && 'anyOf' in sourceObject) { throw new Error(factory_1.messagesFactory.failedToResolvePath.conflictAnyOf(normalizePathForLogging(sourcePath), sourceObject, normalizePathForLogging(path))); } if (sourceObject && typeof sourceObject === 'object' && 'oneOf' in sourceObject) { throw new Error(factory_1.messagesFactory.failedToResolvePath.conflictOneOf(normalizePathForLogging(sourcePath), sourceObject, normalizePathForLogging(path))); } } if (sourceObject && pathKeys.length > 1) { return (0, exports.getObjectPath)(resultObject, pathKeys.slice(1), path); } return resultObject; }; exports.getObjectPath = getObjectPath; const setObjectProp = (sourceObject, path, value) => { const pathKeys = (0, exports.getPathKeys)(path); if (!(pathKeys === null || pathKeys === void 0 ? void 0 : pathKeys.length)) { throw new Error('Not valid path'); } if (pathKeys.length > 1) { // @ts-expect-error if (!sourceObject[pathKeys[0]]) { throw new Error('Not valid path'); } // @ts-expect-error return (0, exports.setObjectProp)(sourceObject[pathKeys[0]], pathKeys.slice(1), value); } if (pathKeys[0]) { // @ts-expect-error sourceObject[pathKeys[0]] = value; } }; exports.setObjectProp = setObjectProp;