private async generateExample()

in lib/generator/exampleGenerator.ts [167:228]


  private async generateExample(operationId: string, specItem: any, rule: ExampleRule) {
    this.translator.setRule(rule);
    this.swaggerMocker.setRule(rule);
    let example;
    console.log(`start generated example for ${operationId}, rule:${rule.ruleName}`);
    if (!this.shouldMock) {
      example = this.getExampleFromPayload(operationId, specItem, rule);
      if (!example) {
        return [];
      }
    } else {
      const xMsExamples = specItem?.content?.["x-ms-examples"] || {};
      const xMsExampleKeys = Object.getOwnPropertyNames(xMsExamples);
      const title = xMsExampleKeys.length > 0 ? xMsExampleKeys[0] : "";
      example = {
        title:
          title.length > 0
            ? title.concat(" - generated by [", rule.ruleName!, "] rule")
            : specItem.content.summary
            ? specItem.content.summary
            : specItem.content.description
            ? specItem.content.description
            : `${operationId}_${rule.exampleNamePostfix}`,
        operationId: operationId,
        parameters: {},
        responses: this.extractResponse(specItem, {}),
      };
      this.swaggerMocker.mockForExample(
        example,
        specItem,
        this.spec,
        util.getBaseName(this.specFilePath).split(".")[0]
      );
    }

    log.info(example);
    const unifiedExample = this.unifyCommonProperty(example);
    const newSpec = util.referenceExmInSpec(
      this.specFilePath,
      specItem.path,
      specItem.methodName,
      `${operationId}_${rule.exampleNamePostfix}_Gen`
    );
    util.updateExmAndSpecFile(
      unifiedExample,
      newSpec,
      this.specFilePath,
      `${operationId}_${rule.exampleNamePostfix}_Gen.json`
    );

    log.info(`start validating generated example for ${operationId}`);
    const validateErrors = await validate.validateExamples(this.specFilePath, operationId, {
      //   consoleLogLevel: "error"
    });
    if (validateErrors.length > 0) {
      log.error(`the validation raised below error:`);
      log.error(validateErrors);
      return validateErrors;
    }
    console.log(`generated example for ${operationId}, rule:${rule.ruleName} successfully!`);
    return [];
  }