"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkErrorType = exports.callCluster = void 0;
exports.errorResponse = errorResponse;
exports.getFileName = getFileName;
exports.joinRequestParams = void 0;
exports.parseOpenSearchErrorResponse = parseOpenSearchErrorResponse;

var _uuid = require("uuid");

/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * OpenSearch error response body:
 *  {
 *   error: {
 *     root_cause: [{ type: 'status_exception', reason: 'test exception' }],
 *     type: 'status_exception',
 *     reason: 'test exception',
 *   },
 *   status: 404,
 * };
 *
 */
function parseOpenSearchErrorResponse(error) {
  if (error.response) {
    try {
      const opensearchErrorResponse = JSON.parse(error.response);
      return opensearchErrorResponse.error.reason || error.response;
    } catch (parsingError) {
      return error.response;
    }
  }

  return error.message;
}

function errorResponse(response, error) {
  return response.custom({
    statusCode: error.statusCode || 500,
    body: parseOpenSearchErrorResponse(error)
  });
}
/**
 * Generate report file name based on name and timestamp.
 * @param itemName      report item name
 * @param timeCreated   timestamp when this is being created
 */


function getFileName(itemName, timeCreated) {
  return `${itemName}_${timeCreated.toISOString()}_${(0, _uuid.v1)()}`;
}
/**
 * Call OpenSearch cluster function.
 * @param client    OpenSearch client
 * @param endpoint  OpenSearch API method
 * @param params    OpenSearch API parameters
 */


const callCluster = async (client, endpoint, params, isScheduledTask) => {
  let opensearchResp;

  if (isScheduledTask) {
    opensearchResp = await client.callAsInternalUser(endpoint, params);
  } else {
    opensearchResp = await client.callAsCurrentUser(endpoint, params);
  }

  return opensearchResp;
};

exports.callCluster = callCluster;

const checkErrorType = error => {
  if (error.statusCode && Math.floor(error.statusCode / 100) === 4) {
    return 'user_error';
  } else {
    return 'system_error';
  }
};

exports.checkErrorType = checkErrorType;

const joinRequestParams = queryParams => {
  if (Array.isArray(queryParams)) return queryParams.join(',');
  if (typeof queryParams === 'string') return queryParams;
  return '';
};

exports.joinRequestParams = joinRequestParams;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 6156 characters]