async onRunQuery()

in public/pages/CreateMonitor/containers/DefineMonitor/DefineMonitor.js [239:300]


  async onRunQuery() {
    const { httpClient, values, notifications } = this.props;
    const formikSnapshot = _.cloneDeep(values);

    const searchType = values.searchType;
    let requests;
    switch (searchType) {
      case SEARCH_TYPE.QUERY:
        requests = [buildSearchRequest(values)];
        break;
      case SEARCH_TYPE.GRAPH:
        // TODO: Might need to check if groupBy is defined if monitor_type === Graph, and prevent onRunQuery() if no group by defined to avoid errors.
        // If we are running a visual graph query, then we need to run two separate queries
        // 1. The actual query that will be saved on the monitor, to get accurate query performance stats
        // 2. The UI generated query that gets [BUCKET_COUNT] times the aggregated buckets to show past history of query
        // If the query is an extraction query, we can use the same query for results and query performance
        requests = [buildSearchRequest(values)];
        requests.push(buildSearchRequest(values, false));
        break;
    }

    try {
      const promises = requests.map((request) => {
        // Fill in monitor name in case it's empty (in create workflow)
        // Set triggers to empty array so they are not executed (if in edit workflow)
        // Set input search to query/graph query and then use execute API to fill in period_start/period_end
        const monitor = formikToMonitor(values);
        _.set(monitor, 'name', 'TEMP_MONITOR');
        _.set(monitor, 'triggers', []);

        switch (searchType) {
          case SEARCH_TYPE.QUERY:
          case SEARCH_TYPE.GRAPH:
            _.set(monitor, 'inputs[0].search', request);
            break;
          default:
            console.log(`Unsupported searchType found: ${JSON.stringify(searchType)}`, searchType);
        }

        return httpClient.post('../api/alerting/monitors/_execute', {
          body: JSON.stringify(monitor),
        });
      });

      const [queryResponse, optionalResponse] = await Promise.all(promises);

      if (queryResponse.ok) {
        const response = _.get(queryResponse.resp, 'input_results.results[0]');
        // If there is an optionalResponse use it's results, otherwise use the original response
        const performanceResponse = optionalResponse
          ? _.get(optionalResponse, 'resp.input_results.results[0]', null)
          : response;
        this.setState({ response, formikSnapshot, performanceResponse });
      } else {
        console.error('There was an error running the query', queryResponse.resp);
        backendErrorNotification(notifications, 'run', 'query', queryResponse.resp);
        this.setState({ response: null, formikSnapshot: null, performanceResponse: null });
      }
    } catch (err) {
      console.error('There was an error running the query', err);
    }
  }