UNPKG

@sudowealth/schwab-api

Version:

TypeScript client for Charles Schwab API with OAuth support, market data, trading functionality, and complete type safety

61 lines (60 loc) 2.81 kB
import { createLogger } from '../utils/secure-logger.js'; import { withRateLimit } from './with-rate-limit.js'; import { withRetry } from './with-retry.js'; import { DEFAULT_TOKEN_AUTH_OPTIONS, withTokenAuth, } from './with-token-auth.js'; const logger = createLogger('Pipeline'); /** * Builds a middleware pipeline from the provided options and token * * @param options Pipeline configuration options * @param token Authentication token or token manager * @returns Array of middleware functions in execution order */ export function buildMiddlewarePipeline(options = {}, tokenManagerInstance) { const pipeline = []; const disabled = options.disable || []; if (options.before && options.before.length > 0) { pipeline.push(...options.before); } if (!disabled.includes('auth') && tokenManagerInstance) { const authOptions = { tokenManager: tokenManagerInstance, // Directly use the passed ETM instance advanced: { ...DEFAULT_TOKEN_AUTH_OPTIONS.advanced, ...options.auth?.advanced, }, }; pipeline.push(withTokenAuth(authOptions)); } else if (!disabled.includes('auth') && tokenManagerInstance === undefined && options.auth !== undefined) { // This case handles if a string token was attempted to be passed via createApiClient options implicitly // Forcing sync, we cannot handle async setup of ETM from string here. logger.error('[buildMiddlewarePipeline] Auth options provided but no ETM instance, and string token setup is async. Auth middleware will be skipped or this should throw.'); // Depending on strictness, you might throw here: // throw new Error("Synchronous buildMiddlewarePipeline requires an EnhancedTokenManager instance for auth; string token setup is async."); } if (options.between?.authAndRateLimit && options.between.authAndRateLimit.length > 0) { pipeline.push(...options.between.authAndRateLimit); } // Add rate limit middleware if not disabled if (!disabled.includes('rateLimit') && options.rateLimit !== false) { pipeline.push(withRateLimit(options.rateLimit || undefined)); } // Add middleware that goes between rate limit and retry if (options.between?.rateLimitAndRetry && options.between.rateLimitAndRetry.length > 0) { pipeline.push(...options.between.rateLimitAndRetry); } // Add retry middleware if not disabled if (!disabled.includes('retry') && options.retry !== false) { pipeline.push(withRetry(options.retry || undefined)); } // Add any custom middleware at the end if (options.custom && options.custom.length > 0) { pipeline.push(...options.custom); } return pipeline; }