@eleva-io/erp-sdk
Version:
SDK oficial para el ERP de Eleva
185 lines • 6.76 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPClient = void 0;
const axios_1 = __importDefault(require("axios"));
const mrmime_1 = require("mrmime");
const signature_1 = require("./signature");
const compatibility_1 = require("./compatibility");
class HTTPClient {
_config;
_logger;
_client;
constructor(_config, _logger) {
this._config = _config;
this._logger = _logger;
this._client = axios_1.default.create({
baseURL: this._config.baseURL,
headers: {
'Content-Type': 'application/json',
},
});
// Interceptor para agregar headers de autenticación
this._client.interceptors.request.use((config) => {
if (config.headers) {
if ('token' in this._config) {
config.headers.set('Authorization', `Bearer ${this._config.token}`);
}
else {
let data = config.data || {};
if (config.data instanceof FormData) {
data = {};
}
const signatureData = (0, signature_1.generateSignature)(data, this._config.apiKey, this._config.apiSecret);
config.headers.set('x-api-key', this._config.apiKey);
config.headers.set('x-timestamp', signatureData.timestamp.toString());
config.headers.set('x-signature', signatureData.signature);
}
}
if (config.data instanceof FormData) {
// Remover Content-Type para que axios lo establezca automáticamente con el boundary
config.headers.delete('Content-Type');
}
// Manejar query params
if (config.params) {
const queryStr = _buildQueryString(config.params);
config.url = `${config.url}?${queryStr}`;
config.params = undefined; // Limpiamos params ya que los incluimos en la URL
}
this._logger.debug(`HTTP REQUEST: [${config.method?.toLocaleUpperCase()}] ${config.url}`);
return config;
});
// Interceptor para manejar respuestas
this._client.interceptors.response.use((response) => {
// Mantener la respuesta original de Axios
return response;
}, (error) => {
const apiError = {
code: error.response?.data?.code || 'UNKNOWN_ERROR',
message: error.response?.data?.message || 'An unexpected error occurred',
errors: error.response?.data?.errors || [],
};
return Promise.reject(apiError);
});
}
async get(path, params) {
const response = await this._client.get(path, { params });
return response.data;
}
async post(path, data, params) {
const response = await this._client.post(path, data, {
params,
});
return response.data;
}
async put(path, data, params) {
const response = await this._client.put(path, data, {
params,
});
return response.data;
}
async patch(path, data, params) {
const response = await this._client.patch(path, data, {
params,
});
return response.data;
}
async delete(path, params) {
const response = await this._client.delete(path, {
params,
});
return response.data;
}
async getBinary(path, params) {
const response = await this._client.get(path, {
params,
responseType: 'arraybuffer',
});
return (0, compatibility_1.createBuffer)(response.data);
}
async form(path, data, method = 'POST', params) {
const fd = _createFormData(data);
const clientMethod = method === 'POST'
? this._client.post.bind(this._client)
: method === 'PUT'
? this._client.put.bind(this._client)
: this._client.patch.bind(this._client);
const response = await clientMethod(path, fd, {
params,
});
return response.data;
}
}
exports.HTTPClient = HTTPClient;
function _createFormData(data) {
const fd = (0, compatibility_1.createFormData)();
Object.entries(data).forEach(([key, value]) => {
if (value === undefined)
return;
if (_isFormFileData(value)) {
const mimeType = (0, mrmime_1.lookup)(value.name);
const file = (0, compatibility_1.createFile)(value.data, value.name, mimeType);
fd.append(key, file, value.name);
}
else if (Array.isArray(value)) {
value.forEach((sv, i) => {
fd.append(`${key}[${i}]`, sv.toString());
});
}
else if (typeof value === 'object' && value !== null) {
Object.entries(value).forEach(([sk, sv]) => {
if (sv === undefined)
return;
fd.append(`${key}[${sk}]`, sv === null ? 'null' : sv.toString());
});
}
else {
fd.append(key, value === null ? 'null' : value.toString());
}
});
return fd;
}
function _deepBuildQuery(acc, obj, prefix) {
Object.entries(obj).forEach(([key, val]) => {
if (!val)
return;
const newPrefix = prefix ? `${prefix}[${key}]` : key;
if (Array.isArray(val)) {
val.forEach((v, i) => {
acc[`${newPrefix}[${i}]`] = v.toString();
});
}
else if (typeof val === 'object' && val !== null) {
_deepBuildQuery(acc, val, newPrefix);
}
else {
acc[newPrefix] = val.toString();
}
});
}
function _buildQueryString(query) {
const reqQuery = {};
Object.entries(query).forEach(([key, value]) => {
if (!value)
return;
if (typeof value === 'object' && value !== null) {
_deepBuildQuery(reqQuery, value, key);
}
else {
reqQuery[key] = value.toString();
}
});
return new URLSearchParams(reqQuery).toString();
}
function _isFormFileData(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return ('name' in value &&
typeof value.name === 'string' &&
'data' in value &&
(typeof value.data === 'string' || (0, compatibility_1.isCrossPlatformBuffer)(value.data)));
}
//# sourceMappingURL=http.js.map