From 2181b40d12b46b00fa14ced4e784c246bd51d4d5 Mon Sep 17 00:00:00 2001 From: Oliver Gupte Date: Tue, 16 Jun 2020 12:20:30 -0700 Subject: [PATCH] moved anomaly job fetch to new function getApmAnomalyDetectionJobs for improved readability and only handle a 404 status code response else throw --- .../lib/service_map/get_service_anomalies.ts | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts index 593191b94dfc1..900141e9040ae 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts @@ -8,12 +8,33 @@ import { leftJoin } from '../../../common/utils/left_join'; import { Job as AnomalyDetectionJob } from '../../../../ml/server'; import { PromiseReturnType } from '../../../typings/common'; import { IEnvOptions } from './get_service_map'; +import { Setup } from '../helpers/setup_request'; import { APM_ML_JOB_GROUP_NAME, encodeForMlApi, } from '../../../common/ml_job_constants'; +async function getApmAnomalyDetectionJobs( + setup: Setup +): Promise { + const { ml } = setup; + + if (!ml) { + return []; + } + try { + const { jobs } = await ml.anomalyDetectors.jobs(APM_ML_JOB_GROUP_NAME); + return jobs; + } catch (error) { + if (error.statusCode === 404) { + return []; + } + throw error; + } +} + type ApmMlJobCategory = NonNullable>; + export const getApmMlJobCategory = ( mlJob: AnomalyDetectionJob, serviceNames: string[] @@ -62,13 +83,7 @@ export async function getServiceAnomalies( return []; } - let apmMlJobs: AnomalyDetectionJob[] = []; - try { - const { jobs } = await ml.anomalyDetectors.jobs(APM_ML_JOB_GROUP_NAME); - apmMlJobs = jobs; - } catch (error) { - // did not find any apm jobs - } + const apmMlJobs = await getApmAnomalyDetectionJobs(options.setup); if (apmMlJobs.length === 0) { return []; }