UNPKG

@stylusapparel/opv3-merchant-api-nodejs

Version:

This is the official NodeJs wrapper for connecting to the StylusOP API V3

86 lines (74 loc) 2.5 kB
const __urlConfig = require('../constants/url'); const { __defaults } = require('../constants/url'); /** * Creates an Http client object based on the auth configuration provided * @param {String} _merchantId - Merchant ID / Client ID * @param {String} _token - Authentication token * @param {Object} config - Configuration object * @returns {Object} HTTP client methods */ const HttpClient = (_merchantId, _token, config = {}) => { const { sandbox = false, merchantName = '', apiVersion = __defaults.LATEST_VERSION, tokenType = 'basic', timeout = 30000, maxRetries = 3 } = config; const _envType = sandbox ? 'sandbox' : 'production'; const _url = __urlConfig[_envType]; // If the "STYLUSOP_API_URL" is set in the environment, use it as the base URL const _baseAPIUrl = process.env.STYLUSOP_API_URL || _url.API_URL; const _configuration = { baseURL: _baseAPIUrl + apiVersion, validateStatus: status => status >= 200 && status < 300 }; if (tokenType === 'jwt' || tokenType === 'bearer') { _configuration.headers = { Authorization: `Bearer ${_token}`, 'Content-Type': 'application/json' }; } else { _configuration.auth = { username: _merchantId || merchantName, password: _token }; } const http = require('axios').create(_configuration); // Add request interceptor http.interceptors.request.use( config => { // Add request timestamp config.metadata = { startTime: new Date() }; return config; }, error => Promise.reject(error) ); // Add response interceptor http.interceptors.response.use( response => { const duration = new Date() - response.config.metadata.startTime; // Log response time if needed // console.log(`Request to ${response.config.url} took ${duration}ms`); return response; }, error => Promise.reject(error) ); // Retry failed requests const retryRequest = async (fn, retries = maxRetries) => { try { return await fn(); } catch (error) { if (retries === 0) throw error; if (error.response?.status >= 500) { return retryRequest(fn, retries - 1); } throw error; } }; return { get: async (url, config = {}) => retryRequest(() => http.get(url, config)), post: async (url, data, config = {}) => retryRequest(() => http.post(url, data, config)), patch: async (url, data, config = {}) => retryRequest(() => http.patch(url, data, config)), put: async (url, data, config = {}) => retryRequest(() => http.put(url, data, config)) }; }; module.exports = HttpClient;