"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useAlertsCount = useAlertsCount; var _react = require("react"); var _useAsyncFn = _interopRequireDefault(require("react-use/lib/useAsyncFn")); var _constants = require("@kbn/rule-registry-plugin/common/constants"); var _public = require("@kbn/kibana-react-plugin/public"); var _ruleDataUtils = require("@kbn/rule-data-utils"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ const ALERT_STATUS = 'kibana.alert.status'; function useAlertsCount({ featureIds, query }) { const { http } = (0, _public.useKibana)().services; const abortCtrlRef = (0, _react.useRef)(new AbortController()); const [state, refetch] = (0, _useAsyncFn.default)(() => { abortCtrlRef.current.abort(); abortCtrlRef.current = new AbortController(); return fetchAlertsCount({ featureIds, query, http, signal: abortCtrlRef.current.signal }); }, [featureIds, query, http], { loading: true }); (0, _react.useEffect)(() => { refetch(); }, [refetch]); const { value: alertsCount, error, loading } = state; return { alertsCount, error, loading, refetch }; } async function fetchAlertsCount({ featureIds, http, query, signal }) { return http.post(`${_constants.BASE_RAC_ALERTS_API_PATH}/find`, { signal, body: JSON.stringify({ aggs: { count: { terms: { field: ALERT_STATUS } } }, feature_ids: featureIds, query, size: 0 }) }).then(extractAlertsCount); } const extractAlertsCount = response => { var _response$aggregation, _ref; const countAggs = (_response$aggregation = response.aggregations) === null || _response$aggregation === void 0 ? void 0 : _response$aggregation.count; const countBuckets = (_ref = countAggs === null || countAggs === void 0 ? void 0 : countAggs.buckets) !== null && _ref !== void 0 ? _ref : []; return countBuckets.reduce((counts, bucket) => { if (bucket.key === _ruleDataUtils.ALERT_STATUS_ACTIVE) { counts.activeAlertCount = bucket.doc_count; } else if (bucket.key === _ruleDataUtils.ALERT_STATUS_RECOVERED) { counts.recoveredAlertCount = bucket.doc_count; } return counts; }, { activeAlertCount: 0, recoveredAlertCount: 0 }); };