"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useRequest = exports.useConditionalRequest = exports.setHttpClient = exports.sendRequestForRq = exports.sendRequest = void 0; var _react = require("react"); var _public = require("@kbn/es-ui-shared-plugin/public"); /* * 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. */ let httpClient; const setHttpClient = client => { httpClient = client; }; exports.setHttpClient = setHttpClient; const sendRequest = config => { if (!httpClient) { throw new Error('sendRequest has no http client set'); } return (0, _public.sendRequest)(httpClient, config); }; // Sends requests with better ergonomics for React Query, e.g. throw error rather // than resolving with an `error` property in the result. Also returns `data` directly // as opposed to { data } in a response object. exports.sendRequest = sendRequest; const sendRequestForRq = async config => { if (!httpClient) { throw new Error('sendRequest has no http client set'); } const response = await (0, _public.sendRequest)(httpClient, config); if (response.error) { throw response.error; } // Data can't be null so long as `_sendRequest` did not throw return response.data; }; exports.sendRequestForRq = sendRequestForRq; const useRequest = config => { if (!httpClient) { throw new Error('sendRequest has no http client set'); } return (0, _public.useRequest)(httpClient, config); }; exports.useRequest = useRequest; const useConditionalRequest = config => { const [state, setState] = (0, _react.useState)({ error: null, data: null, isLoading: false }); const { path, method, shouldSendRequest, query, body } = config; async function sendGetOneEnrollmentAPIKeyRequest() { if (!config.shouldSendRequest) { setState({ data: null, isLoading: false, error: null }); return; } try { setState({ data: null, isLoading: true, error: null }); const res = await sendRequest({ method: config.method, path: config.path, query: config.query, body: config.body }); if (res.error) { throw res.error; } setState({ data: res.data, isLoading: false, error: null }); return res; } catch (error) { setState({ data: null, isLoading: false, error }); } } (0, _react.useEffect)(() => { sendGetOneEnrollmentAPIKeyRequest(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [path, method, shouldSendRequest, JSON.stringify(query), JSON.stringify(body)]); return { ...state, sendRequest: sendGetOneEnrollmentAPIKeyRequest }; }; exports.useConditionalRequest = useConditionalRequest;