UNPKG

tradestation-api-ts

Version:

A comprehensive TypeScript wrapper for TradeStation WebAPI v3

73 lines (72 loc) 2.83 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 TokenManager_1 = require("../utils/TokenManager"); const RateLimiter_1 = require("../utils/RateLimiter"); class HttpClient { constructor(config) { this.tokenManager = new TokenManager_1.TokenManager(config); this.rateLimiter = new RateLimiter_1.RateLimiter(); // Determine base URL based on environment const baseURL = config?.environment?.toLowerCase() === 'simulation' ? 'https://sim.api.tradestation.com' : 'https://api.tradestation.com'; this.axiosInstance = axios_1.default.create({ baseURL, headers: { 'Content-Type': 'application/json', }, }); // Add request interceptor for authentication this.axiosInstance.interceptors.request.use(async (config) => { // Wait for rate limiting slot if (config.url) { await this.rateLimiter.waitForSlot(config.url); } // Get valid token (will refresh if needed) const token = await this.tokenManager.getValidAccessToken(); config.headers.Authorization = `Bearer ${token}`; return config; }, (error) => Promise.reject(error)); // Add response interceptor for rate limit headers this.axiosInstance.interceptors.response.use((response) => { if (response.config.url) { this.rateLimiter.updateLimits(response.config.url, response.headers); } return response; }, (error) => Promise.reject(error)); } /** * Gets the current refresh token * @returns The current refresh token or null if none is available */ getRefreshToken() { return this.tokenManager.getRefreshToken(); } async get(url, config) { return this.axiosInstance.get(url, config); } async post(url, data, config) { return this.axiosInstance.post(url, data, config); } async put(url, data, config) { return this.axiosInstance.put(url, data, config); } async delete(url, config) { return this.axiosInstance.delete(url, config); } // Method for handling streaming endpoints createStream(url, config) { return new Promise((resolve, reject) => { this.axiosInstance .get(url, { ...config, responseType: 'stream' }) .then((response) => resolve(response.data)) .catch(reject); }); } } exports.HttpClient = HttpClient;