UNPKG

digi-tech-sdk

Version:

SDK oficial para integrar con la API de Digi

155 lines (154 loc) 6.86 kB
"use strict"; 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 axios_retry_1 = __importDefault(require("axios-retry")); class HttpClient { constructor(config, authManager) { this.authManager = authManager; this.baseUrl = this.getBaseUrl(config.environment); // Create Axios instance this.client = axios_1.default.create({ baseURL: this.baseUrl, timeout: config.timeout || 10000, }); // Configure retry logic (0, axios_retry_1.default)(this.client, { retries: config.maxRetries || 3, retryDelay: axios_retry_1.default.exponentialDelay, retryCondition: (error) => { var _a; // Only retry on network errors or 5xx errors (except 401 which will be handled separately) if (axios_retry_1.default.isNetworkOrIdempotentRequestError(error)) { return true; } if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) && error.response.status >= 500) { return true; } // Explicitly return false for all other cases return false; } }); // Add auth token to requests this.client.interceptors.request.use(async (config) => { var _a; // If the URL isn't already handling auth (like the auth endpoint itself) if (!((_a = config.url) === null || _a === void 0 ? void 0 : _a.includes('/authorization/'))) { // Always ensure we have a fresh token let token = await this.authManager.getToken(); // Double-check the token is valid - if not, force a fresh token if (!token) { console.warn('Token is undefined, forcing fresh token fetch'); token = await this.authManager.fetchNewToken(); if (!token) { console.error('Failed to obtain authentication token'); throw new Error('Authentication failed - unable to obtain token'); } } // Ensure params object exists if (!config.params) { config.params = {}; } // Explicitly add authorization token as a query parameter config.params.authorization = token; // For debugging - log the URL with params console.log(`Request URL: ${config.url} with params:`, config.params); } return config; }); // Handle 401 responses this.client.interceptors.response.use((response) => { // Reset retry flag on success this.authManager.resetAuthRetry(); return response; }, async (error) => { var _a, _b, _c, _d; console.error('Request failed:', (_a = error.response) === null || _a === void 0 ? void 0 : _a.status, (_b = error.config) === null || _b === void 0 ? void 0 : _b.url); // If we get a 401 or 500 and haven't retried yet if (((_c = error.response) === null || _c === void 0 ? void 0 : _c.status) === 401 || ((_d = error.response) === null || _d === void 0 ? void 0 : _d.status) === 500) { if (!this.authManager.hasRetried()) { console.log('Retrying with new token...'); this.authManager.markRetry(); // Get a fresh token const token = await this.authManager.fetchNewToken(); if (!token) { console.error('Failed to obtain new authentication token for retry'); return Promise.reject(new Error('Authentication failed - unable to obtain token for retry')); } // Retry the original request const config = error.config; config.params = config.params || {}; config.params.authorization = token; console.log(`Retry with token: ${config.params.authorization}`); return this.client(config); } } return Promise.reject(error); }); } getBaseUrl(environment) { switch (environment) { case 'qa': return 'https://api.qa.digiventures.la'; case 'staging': return 'https://api.staging.digiventures.la'; case 'production': return 'https://api.production.digiventures.la'; default: throw new Error(`Invalid environment: ${environment}`); } } async get(url, config) { // Ensure config has params for authorization if (!config) config = {}; if (!config.params) config.params = {}; // Always ensure we have a valid token if (!config.params.authorization) { const token = await this.authManager.getToken(); if (!token) { throw new Error('Authentication token is undefined - unable to make request'); } config.params.authorization = token; } return this.client.get(url, config); } async post(url, data, config) { // Ensure config has params for authorization if (!config) config = {}; if (!config.params) config.params = {}; // Always ensure we have a valid token if (!config.params.authorization) { const token = await this.authManager.getToken(); if (!token) { throw new Error('Authentication token is undefined - unable to make request'); } config.params.authorization = token; } return this.client.post(url, data, config); } async put(url, data, config) { // Ensure config has params for authorization if (!config) config = {}; if (!config.params) config.params = {}; // Always ensure we have a valid token if (!config.params.authorization) { const token = await this.authManager.getToken(); if (!token) { throw new Error('Authentication token is undefined - unable to make request'); } config.params.authorization = token; } return this.client.put(url, data, config); } } exports.HttpClient = HttpClient;