export function safeSetObjectPropertyValue()

in libs/logic-apps-shared/src/utils/src/lib/helpers/functions.ts [308:356]


export function safeSetObjectPropertyValue(
  target: Record<string, any> | null | undefined,
  properties: string[],
  value: any,
  merge = false
): Record<string, any> | null | undefined {
  if (properties.includes('__proto__') || properties.includes('constructor')) {
    throw new Error('attempting to access protected properties');
  }
  if (!properties.length) {
    return value;
  }

  const tgt = target || {};

  let current = tgt;
  for (let i = 0; i < properties.length - 1; i++) {
    const parent = current;
    const propertyName = properties[i];
    current = getPropertyValue(current, propertyName);
    if (typeof current !== 'object') {
      current = {};
      parent[propertyName] = current;
    }
  }

  let property = properties[properties.length - 1];
  for (const key of Object.keys(current)) {
    if (equals(key, property)) {
      property = key;
      break;
    }
  }

  // if merge flag is set, do a deep merge of the current value to the target source.
  if (merge) {
    if (typeof current[property] === 'object' && typeof value === 'object') {
      deepMerge(current[property], value);
    } else if (property === 'body' && typeof current[property] === 'object') {
      deepMerge(current[property], value.properties);
    } else {
      current[property] = value;
    }
  } else {
    current[property] = value;
  }

  return tgt;
}