API Reference

Complete documentation for hyperwiz API. Explore all methods, configuration options, and TypeScript definitions to build secure applications.

Type Safe

Full TypeScript support with intelligent types

Lightweight

Small bundle size with no unnecessary dependencies

Auto Retry

Adaptive backoff with exponential delay

Smart Caching

In-memory or IndexedDB caching with auto-expiration

API Methods

Complete reference for all hyperwiz functions

createClient(baseUrl, config?)

Creates an HTTP client instance with optional configuration.

TypeScript

const api = createClient('https://api.example.com', {
  logging: true,           // Enable request/response logging
  timeout: 30000,          // Request timeout in milliseconds
  credentials: 'include',  // Credentials mode for cross-origin
  retry: true,             // Auto retry (boolean) or retry config object
  // retry: {              // Custom retry configuration
  //   maxRetries: 3,      // Maximum retry attempts
  //   retryDelay: 1000,   // Initial delay in milliseconds
  //   maxDelay: 10000,    // Maximum delay in milliseconds
  //   backoffMultiplier: 2, // Exponential backoff multiplier
  //   retryOnStatus: [408, 429, 500, 502, 503, 504], // HTTP status codes to retry
  //   retryOnNetworkError: true // Retry on network errors
  // },
  cache: true,             // Smart caching (boolean) or cache config object
  // cache: {              // Custom cache configuration
  //   enabled: true,      // Enable caching
  //   maxAge: 5 * 60 * 1000, // Cache duration in milliseconds (5 minutes)
  //   maxSize: 50,        // Maximum number of cached items
  //   storage: 'memory',  // Storage type: 'memory' or 'indexeddb'
  //   includeQueryParams: true, // Include query params in cache key
  //   cacheableMethods: ['GET', 'HEAD'], // HTTP methods to cache
  //   cacheableStatusCodes: [200, 304]   // Status codes to cache
  // }
});

JavaScript

const api = createClient('https://api.example.com', {
  logging: true,           // Enable request/response logging
  timeout: 30000,          // Request timeout in milliseconds
  credentials: 'include',  // Credentials mode for cross-origin
  retry: true,             // Auto retry (boolean) or retry config object
  // retry: {              // Custom retry configuration
  //   maxRetries: 3,      // Maximum retry attempts
  //   retryDelay: 1000,   // Initial delay in milliseconds
  //   maxDelay: 10000,    // Maximum delay in milliseconds
  //   backoffMultiplier: 2, // Exponential backoff multiplier
  //   retryOnStatus: [408, 429, 500, 502, 503, 504], // HTTP status codes to retry
  //   retryOnNetworkError: true // Retry on network errors
  // },
  cache: true,             // Smart caching (boolean) or cache config object
  // cache: {              // Custom cache configuration
  //   enabled: true,      // Enable caching
  //   maxAge: 5 * 60 * 1000, // Cache duration in milliseconds (5 minutes)
  //   maxSize: 50,        // Maximum number of cached items
  //   storage: 'memory',  // Storage type: 'memory' or 'indexeddb'
  //   includeQueryParams: true, // Include query params in cache key
  //   cacheableMethods: ['GET', 'HEAD'], // HTTP methods to cache
  //   cacheableStatusCodes: [200, 304]   // Status codes to cache
  // }
});

HTTP Methods

All HTTP methods return Promise<ApiResponse<T>> with consistent response format.

TypeScript

// All methods return Promise<ApiResponse<T>>
api.get<T>(url: string, headers?: HeadersInit)
api.post<T>(url: string, body: unknown, headers?: HeadersInit)
api.put<T>(url: string, body: unknown, headers?: HeadersInit)
api.patch<T>(url: string, body: unknown, headers?: HeadersInit)
api.delete<T>(url: string, headers?: HeadersInit)

// Example usage
const users = await api.get<User[]>('/users');
const newUser = await api.post<User>('/users', { name: 'John' });
const updatedUser = await api.put<User>('/users/1', { name: 'John Updated' });
const deleted = await api.delete('/users/1');

// Response format
type ApiResponse<T> = 
  | { success: true; data: T }
  | { success: false; status?: number; error: string };

JavaScript

// All methods return Promise<ApiResponse<T>>
api.get(url, headers)
api.post(url, body, headers)
api.put(url, body, headers)
api.patch(url, body, headers)
api.delete(url, headers)

// Example usage
const users = await api.get('/users');
const newUser = await api.post('/users', { name: 'John' });
const updatedUser = await api.put('/users/1', { name: 'John Updated' });
const deleted = await api.delete('/users/1');

// Response format
// { success: true, data: ... } or { success: false, error: ... }

Interceptor Methods

Add request, response, and error interceptors for complete control.

TypeScript

// Add interceptors
api.addBefore(handler: RequestHandler)
api.addAfter(handler: ResponseHandler)
api.addErrorHandler(handler: ErrorHandler)

// Remove interceptors
api.removeBefore(handler: RequestHandler)
api.removeAfter(handler: ResponseHandler)
api.removeErrorHandler(handler: ErrorHandler)

// Clear all interceptors
api.clearInterceptors()

// Set timeout
api.setTimeout(timeoutMs: number)

// Cancel all requests
api.cancelAllRequests()

// Example: Add token interceptor
api.addBefore((config, url) => {
  const token = localStorage.getItem('token');
  if (token) {
    return {
      ...config,
      headers: {
        ...config.headers,
        'Authorization': `Bearer ${token}`
      }
    };
  }
  return config;
});

JavaScript

// Add interceptors
api.addBefore(handler)
api.addAfter(handler)
api.addErrorHandler(handler)

// Remove interceptors
api.removeBefore(handler)
api.removeAfter(handler)
api.removeErrorHandler(handler)

// Clear all interceptors
api.clearInterceptors()

// Set timeout
api.setTimeout(timeoutMs)

// Cancel all requests
api.cancelAllRequests()

// Example: Add token interceptor
api.addBefore((config, url) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers = {
      ...config.headers,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
});

Configuration Options

Complete configuration options for the HTTP client.

TypeScript

interface ClientConfig {
  logging?: boolean;           // Enable request/response logging
  timeout?: number;            // Request timeout in milliseconds
  credentials?: RequestCredentials; // 'omit' | 'same-origin' | 'include'
  retry?: boolean | RetryConfig;   // Auto retry configuration
  cache?: boolean | CacheConfig;   // Smart caching configuration
}

interface RetryConfig {
  maxRetries: number;          // Maximum retry attempts
  retryDelay: number;          // Initial delay in milliseconds
  maxDelay: number;            // Maximum delay in milliseconds
  backoffMultiplier: number;   // Exponential backoff multiplier
  retryOnStatus: number[];     // HTTP status codes to retry
  retryOnNetworkError: boolean; // Retry on network errors
}

interface CacheConfig {
  enabled: boolean;            // Enable caching
  maxAge: number;              // Cache duration in milliseconds
  maxSize: number;             // Maximum number of cached items
  storage: 'memory' | 'indexeddb'; // Storage type
  includeQueryParams: boolean; // Include query params in cache key
  cacheableMethods: string[];  // HTTP methods to cache
  cacheableStatusCodes: number[]; // Status codes to cache
}

// Example configurations
const simpleConfig = {
  logging: true,
  retry: true,
  cache: true
};

const advancedConfig = {
  logging: true,
  timeout: 30000,
  credentials: 'include',
  retry: {
    maxRetries: 5,
    retryDelay: 500,
    maxDelay: 5000,
    backoffMultiplier: 1.5,
    retryOnStatus: [500, 502, 503, 504],
    retryOnNetworkError: true
  },
  cache: {
    enabled: true,
    maxAge: 10 * 60 * 1000,  // 10 minutes
    maxSize: 50,
    storage: 'indexeddb',
    includeQueryParams: true,
    cacheableMethods: ['GET', 'HEAD'],
    cacheableStatusCodes: [200, 304]
  }
};

JavaScript

// Configuration options
const config = {
  logging: true,           // Enable request/response logging
  timeout: 30000,          // Request timeout in milliseconds
  credentials: 'include',  // Credentials mode for cross-origin
  retry: true,             // Auto retry (boolean) or retry config object
  // retry: {              // Custom retry configuration
  //   maxRetries: 3,      // Maximum retry attempts
  //   retryDelay: 1000,   // Initial delay in milliseconds
  //   maxDelay: 10000,    // Maximum delay in milliseconds
  //   backoffMultiplier: 2, // Exponential backoff multiplier
  //   retryOnStatus: [408, 429, 500, 502, 503, 504], // HTTP status codes to retry
  //   retryOnNetworkError: true // Retry on network errors
  // },
  cache: true,             // Smart caching (boolean) or cache config object
  // cache: {              // Custom cache configuration
  //   enabled: true,      // Enable caching
  //   maxAge: 5 * 60 * 1000, // Cache duration in milliseconds (5 minutes)
  //   maxSize: 50,        // Maximum number of cached items
  //   storage: 'memory',  // Storage type: 'memory' or 'indexeddb'
  //   includeQueryParams: true, // Include query params in cache key
  //   cacheableMethods: ['GET', 'HEAD'], // HTTP methods to cache
  //   cacheableStatusCodes: [200, 304]   // Status codes to cache
  // }
};

// Example configurations
const simpleConfig = {
  logging: true,
  retry: true,
  cache: true
};

const advancedConfig = {
  logging: true,
  timeout: 30000,
  credentials: 'include',
  retry: {
    maxRetries: 5,
    retryDelay: 500,
    maxDelay: 5000,
    backoffMultiplier: 1.5,
    retryOnStatus: [500, 502, 503, 504],
    retryOnNetworkError: true
  },
  cache: {
    enabled: true,
    maxAge: 10 * 60 * 1000,  // 10 minutes
    maxSize: 50,
    storage: 'indexeddb',
    includeQueryParams: true,
    cacheableMethods: ['GET', 'HEAD'],
    cacheableStatusCodes: [200, 304]
  }
};

Type Definitions

TypeScript type definitions for interceptors and responses.

TypeScript

// Interceptor types
type RequestHandler = (config: RequestConfig, url: string) => RequestConfig;
type ResponseHandler = (response: Response, data: any, url: string) => any;
type ErrorHandler = (error: any, url: string, requestConfig?: RequestConfig) => any;

interface RequestConfig {
  method: string;
  headers: HeadersInit;
  body?: any;
  timeout?: number;
  credentials?: RequestCredentials;
}

// Response types
type ApiResponse<T> = 
  | { success: true; data: T }
  | { success: false; status?: number; error: string };

// Example with types
interface User {
  id: number;
  name: string;
  email: string;
}

const api = createClient('https://api.example.com');

// TypeScript knows the response type
const users = await api.get<User[]>('/users');
if (users.success) {
  users.data.forEach(user => {
    console.log(user.name); // TypeScript autocomplete works
  });
}

JavaScript

// JavaScript usage (types are inferred)
const api = createClient('https://api.example.com');

// All responses follow the same format
const users = await api.get('/users');
if (users.success) {
  users.data.forEach(user => {
    console.log(user.name);
  });
} else {
  console.error('Error:', users.error);
}

// Response format
// { success: true, data: ... } or { success: false, error: ... }