All files / src/api users.js

50% Statements 14/28
37.93% Branches 11/29
33.33% Functions 1/3
50% Lines 14/28

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128                                                    2x 5x   5x 1x             4x         4x 4x           2x 1x             1x         3x 2x   1x                                                   2x                                                                        
import { httpRequest } from "../utils/httpClient";
import { ApacuanaAPIError } from "../errors/index";
import { getConfig } from "../config/index";
import ApacuanaSuccess from "../success";
 
/**
 * @typedef {object} GetCustomerData
 * @property {string} token - El token de sesión del usuario.
 * @property {object} userData - Los datos del usuario obtenidos.
 */
 
/**
 * @typedef {object} GetCustomerResponse
 * @property {true} success - Indica que la operación fue exitosa.
 * @property {GetCustomerData} data - El payload de la respuesta.
 */
 
/**
 * 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>} Una promesa que resuelve a un objeto con la respuesta exitosa.
 * @throws {Error} Si los parámetros de entrada son inválidos.
 * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
 */
export 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 new ApacuanaSuccess({
      token: response.sessionid,
      userData: response.entry,
    });
  } catch (error) {
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new ApacuanaAPIError(
      `Unexpected failure getting token: ${error.message || "Unknown error"}`
    );
  }
};
 
/**
 * @typedef {object} CreateUserPayload
 * @property {string} usr - Correo electrónico del usuario.
 * @property {string} pwd - Contraseña del usuario.
 * @property {string} kinddoc - Tipo de documento de identidad (ej. 'V', 'P', 'E').
 * @property {string} doc - Número de documento de identidad.
 */
 
/**
 * @typedef {object} CreateUserResponse
 * @property {string} message - Mensaje de confirmación de la creación del usuario.
 */
 
/**
 * Crea un nuevo usuario en la plataforma de Apacuana.
 * @param {CreateUserPayload} userData - Objeto con los datos del usuario a crear.
 * @returns {Promise<ApacuanaSuccess>} Una promesa que resuelve a un objeto con la respuesta exitosa.
 * @throws {ApacuanaAPIError} Si los datos de entrada son inválidos o si ocurre un error en la API.
 */
 
export const createApacuanaUser = async (userData) => {
  try {
    const formData = new FormData();
    Object.keys(userData).forEach((key) => {
      const value = userData[key];
      const isRNFile =
        value &&
        typeof value === "object" &&
        value.uri &&
        value.name &&
        value.type;
      if (value instanceof File || isRNFile) {
        formData.append(key, value);
      } else if (value !== null && value !== undefined) {
        formData.append(key, String(value));
      }
    });
 
    const response = await httpRequest(
      "services/api/register/initial",
      formData,
      "POST"
    );
 
    return new ApacuanaSuccess({
      ...response,
    });
  } catch (error) {
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new ApacuanaAPIError(
      `Unexpected failure creating user: ${error.message || "Unknown error"}`
    );
  }
};