All files / api users.js

100% Statements 13/13
91.66% Branches 11/12
100% Functions 1/1
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                        1x 5x   5x 1x             4x         4x 4x           2x 1x             1x           3x 2x   1x                  
import { httpRequest } from "../utils/httpClient";
import { ApacuanaAPIError } from "../errors/index";
import { getConfig } from "../config/index";
 
/**
 * @typedef {object} GetCustomerResponse
 * @property {string} token - El token de sesión del usuario.
 * @property {object} userData - Los datos del usuario obtenidos.
 * @property {boolean} success - Indica si la operación fue exitosa.
 */
 
/**
 * Obtiene el token de un usuario a través de una petición POST.
 * Este método es útil para endpoints que requieren datos en el cuerpo de la petición
 * para buscar un usuario, como un ID de sesión o un token de acceso.
 *
 * @returns {Promise<GetCustomerResponse>} Objeto con el token de sesión, los datos del usuario y un indicador de éxito.
 * @throws {Error} Si los parámetros de entrada son inválidos.
 * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
 */
const getCustomer = async () => {
  const { verificationId, customerId } = getConfig();
 
  if (!verificationId || !customerId) {
    throw new ApacuanaAPIError(
      "Both 'verificationId' and 'customerId' must be configured.",
      400,
      "CONFIGURATION_ERROR"
    );
  }
 
  const body = {
    verificationid: verificationId,
    customerid: customerId,
  };
 
  try {
    const response = await httpRequest(
      "services/api/register/init",
      body,
      "POST"
    );
 
    if (!response.sessionid || !response.entry) {
      throw new ApacuanaAPIError(
        "The API response does not contain the user.",
        200,
        "INVALID_API_RESPONSE"
      );
    }
 
    return {
      token: response.sessionid,
      userData: response.entry,
      success: true,
    };
  } catch (error) {
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new ApacuanaAPIError(
      `Unexpected failure getting token: ${
        error.message || "Unknown error"
      }`
    );
  }
};
 
export default getCustomer;