UNPKG

pink-bears

Version:

Intelligent rate limiting middleware with MongoDB integration and caching for Node.js applications

77 lines (70 loc) 2.54 kB
const axios = require('axios'); class AxiosWrapper { constructor(domain, productKey) { this.domain = domain; this.productKey = productKey; this.axiosInstance = axios.create({ timeout: 30000, }); // Set up the interceptors //this._initializeRequestInterceptor(); this._initializeResponseInterceptor(); } // Method to initialize the request interceptor // _initializeRequestInterceptor() { // this.axiosInstance.interceptors.request.use( // (config) => { // return config; // }, // (error) => Promise.reject(error) // ); // } // Method to initialize the response interceptor _initializeResponseInterceptor() { this.axiosInstance.interceptors.response.use( (response) => { return response; }, async (error) => { const originalRequest = error.config; // If the response is 401 Unauthorized, handle token refresh if (error.response && error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = true; const newToken = await this.refreshAuthToken(); // Refresh token logic if (newToken) { originalRequest.headers['auth'] = newToken; return this.axiosInstance(originalRequest); // Retry the request } } return Promise.reject(error); // Propagate other errors } ); } // Placeholder: Replace this with your actual token refresh logic async refreshAuthToken() { try { // Example token refresh request const response = await axios.post( `${this.domain}/api/authenticate`, { productKey: this.productKey }, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.productToken}` }, } ); return response?.data?.Access_Token; } catch (err) { console.error('Error refreshing token:', err); return null; } } // Function to return the axios instance getAxiosInstance() { return this.axiosInstance; } } module.exports = AxiosWrapper;