@apideck/portman
Version:
Port OpenAPI Spec to Postman Collection, with contract & variation tests included
48 lines • 1.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.setByPath = void 0;
var tslib_1 = require("tslib");
var dot_object_1 = tslib_1.__importDefault(require("dot-object"));
var isObject_1 = require("./isObject");
var setByPath = function (objectOrArray, path, newValue) {
var _a;
if (!(0, isObject_1.isObject)(objectOrArray) && !Array.isArray(objectOrArray))
return objectOrArray;
var dot = new dot_object_1.default();
var arrayPathCheck = path.endsWith(']');
var indexKey = (_a = path.match(/\d+/g)) === null || _a === void 0 ? void 0 : _a[0];
if (Array.isArray(newValue)) {
dot.keepArray = true;
}
var currentValue = dot.pick(path, objectOrArray);
if ((0, isObject_1.isObject)(currentValue) && !(0, isObject_1.isObject)(newValue)) {
dot.del(path, objectOrArray);
}
if (Array.isArray(objectOrArray)) {
if (indexKey && objectOrArray[indexKey] && !path.includes('.') && arrayPathCheck) {
objectOrArray[indexKey] = newValue;
return objectOrArray;
}
if (indexKey && objectOrArray[indexKey] && path.includes('.') && arrayPathCheck) {
var item = objectOrArray[indexKey];
var subPath = path.substring(path.indexOf('.') + 1);
if (subPath) {
objectOrArray[indexKey] = dot.str(subPath, newValue, item);
return objectOrArray;
}
}
var flatInput = dot.dot(objectOrArray);
if (!arrayPathCheck) {
flatInput[path] = newValue;
var res = dot.object(flatInput);
return res[Object.keys(res)[0]];
}
}
if (path.match(/\[\d+\]/)) {
var arrayPath = path.replace(/\[(\d+)\]/g, '.$1');
return dot.str(arrayPath, newValue, objectOrArray);
}
return dot.str(path, newValue, objectOrArray);
};
exports.setByPath = setByPath;
//# sourceMappingURL=setByPath.js.map