Vana SDK - v2.2.2
    Preparing search index...

    Class ApiClient

    Provides resilient HTTP client functionality with enterprise features.

    This client implements multiple resilience patterns to ensure reliable API communication even under adverse conditions. It automatically handles transient failures, rate limits, and service outages while providing hooks for custom behavior through middleware.

    Features:

    • Automatic retry with exponential backoff
    • Rate limiting to prevent API throttling
    • Circuit breaker for fast failure detection
    • Middleware pipeline for request/response transformation
    • Configurable timeouts and headers
    // Create client with custom configuration
    const client = new ApiClient({
    baseUrl: 'https://api.example.com',
    headers: { 'API-Key': 'secret' },
    retry: {
    maxAttempts: 5,
    baseDelay: 2000
    },
    rateLimit: {
    requestsPerWindow: 50,
    windowMs: 60000
    }
    });

    // Add logging middleware
    client.use(async (req, next) => {
    console.log(`Request: ${req.params.url}`);
    const res = await next(req);
    console.log(`Response: ${res.status}`);
    return res;
    });

    // Make resilient API calls
    const data = await client.get('/users');
    Index

    Methods

    • Adds middleware to the request processing pipeline.

      Parameters

      • middleware: Middleware

        The middleware function to add to the pipeline

      Returns void

      Middleware functions execute in order of registration and can transform requests, responses, or implement cross-cutting concerns like logging, authentication, or caching.

      // Add authentication middleware
      client.use(async (req, next) => {
      req.options.headers = {
      ...req.options.headers,
      'Authorization': `Bearer ${getToken()}`
      };
      return next(req);
      });

      // Add response caching
      client.use(async (req, next) => {
      const cached = cache.get(req.params.url);
      if (cached) return cached;

      const res = await next(req);
      if (res.status === 'success') {
      cache.set(req.params.url, res);
      }
      return res;
      });
    • Executes an HTTP request with full resilience features.

      Type Parameters

      • TData = unknown

      Parameters

      • url: string

        The URL to make the request to. Can be relative (uses baseUrl) or absolute.

      • options: RequestOptions = {}

        Request options including method, headers, body, etc.

      Returns Promise<GenericResponse<TData, unknown>>

      Promise resolving to the response data

      This is the core request method that applies all configured resilience patterns including retry, rate limiting, and circuit breaking. It processes the request through the middleware pipeline before execution.

      When request fails after all retry attempts. Check error message for details.

      When circuit breaker is open. Wait for recovery timeout before retrying.

      const response = await client.request('/api/data', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      params: { name: 'John', age: 30 },
      timeout: 5000
      });

    post

    • Get client statistics

      Returns {
          rateLimiter: { remaining: number; resetTime: number } | null;
          circuitBreaker: { state: string; failures: number } | null;
          middleware: { count: number };
      }

      Object containing client statistics and performance metrics