private convertVariables()

in lib/apiScenario/gen/testRecordingApiScenarioGenerator.ts [425:510]


  private convertVariables(
    root: Scenario["variables"],
    scopes: Array<RawVariableScope & { operation?: Operation }>
  ) {
    const keyToVariables = new Map<string, Variable[]>();
    const unusedVariables = new Set<string>();
    scopes.forEach((v) => {
      Object.entries(v.variables ?? {}).forEach(([key, value]) => {
        value = value as Variable;
        key = `${key}_${typeMap[value.type]}`;
        if (value.type === "string") {
          key = `${key}_${value.value}`;
        }
        const vars = keyToVariables.get(key) ?? [];
        vars.push(value);
        keyToVariables.set(key, vars);
      });
      v.operation?.parameters?.forEach((p) => {
        const param = this.jsonLoader.resolveRefObj(p);
        if (v.variables?.[param.name] === undefined) {
          unusedVariables.add(`${param.name}`);
        }
      });
      delete v.operation;
    });

    keyToVariables.forEach((vars, key) => {
      if (vars.length === 1 || unusedVariables.has(key.split("_")[0])) {
        return;
      }
      const old = cloneDeep(vars[0]);
      const [keyName] = key.split("_");
      if (old.type === "string") {
        if (unreplaceWords.includes(old.value!)) {
          return;
        }
        if (root[keyName] !== undefined) {
          for (let i = 1; ; i++) {
            key = `${keyName}${i}`;
            if (root[key] === undefined) {
              break;
            }
          }
        } else {
          key = keyName;
        }
        root[key] = old;
        replaceAllString(old.value!, key, scopes);
      }
      if (root[keyName] !== undefined) {
        return;
      }
      root[keyName] = old;

      if (old.type === "object" || old.type === "array") {
        for (const newValue of vars) {
          const diff = getJsonPatchDiff(old.value!, newValue.value!);
          if (
            diff.length > 0 &&
            newValue.type == old.type &&
            diff.filter((d) => Object.keys(d).includes("remove")).length <= 2
          ) {
            newValue.patches = diff;
            newValue.value = undefined;
          }

          if (diff.length === 0) {
            newValue.value = undefined;
          }
        }
      }
    });

    scopes.forEach((v) => {
      Object.keys(v.variables ?? {}).forEach((key) => {
        const variable = v.variables![key] as Variable;
        if (variable.type === "array" || variable.type === "object") {
          if (variable.patches === undefined && variable.value === undefined) {
            delete v.variables![key];
          }
        } else if (root[key] && root[key].value === variable.value) {
          delete v.variables![key];
        }
      });
    });
  }