npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@chittyos/http-client

v1.0.1

Published

Type-safe HTTP client with retry logic for ChittyOS Framework

Downloads

18

Readme

@chittyos/http-client

Type-safe HTTP client with retry logic for ChittyOS Framework.

Installation

npm install @chittyos/http-client

Usage

Basic Usage

import { HttpClient } from '@chittyos/http-client';

// Create client with base URL
const client = new HttpClient({
  baseURL: 'https://api.example.com',
  timeout: 30000,
  headers: {
    'Authorization': 'Bearer token',
  },
});

// Make requests
const users = await client.get('/users');
const newUser = await client.post('/users', { name: 'John' });
const updated = await client.put('/users/123', { name: 'Jane' });
await client.delete('/users/123');

ChittyOS HTTP Client

import { createChittyOSHttpClient } from '@chittyos/http-client';

// Create client with ChittyOS defaults
const client = createChittyOSHttpClient({
  baseURL: 'https://api.chitty.cc',
});

// Includes automatic retry logic and ChittyOS headers
const response = await client.get('/health');

Service-Specific Client

import { createServiceHttpClient } from '@chittyos/http-client';

// Create client for specific ChittyOS service
const chittyidClient = createServiceHttpClient(
  'chittyid',
  'https://id.chitty.cc'
);

// Automatically includes service identifier in headers
const id = await chittyidClient.post('/v1/mint', {
  entity: 'PEO',
  trust: 'verified',
});

HTTP Methods

import { HttpClient } from '@chittyos/http-client';

const client = new HttpClient({ baseURL: 'https://api.example.com' });

// GET request
const users = await client.get<User[]>('/users');

// POST request with body
const newUser = await client.post<User>('/users', {
  name: 'John',
  email: '[email protected]',
});

// PUT request
const updated = await client.put<User>('/users/123', {
  name: 'Jane',
});

// PATCH request
const patched = await client.patch<User>('/users/123', {
  active: false,
});

// DELETE request
await client.delete('/users/123');

// HEAD request
await client.head('/users/123');

Retry Configuration

import { createChittyOSHttpClient } from '@chittyos/http-client';

const client = createChittyOSHttpClient({
  baseURL: 'https://api.example.com',
  retry: {
    maxRetries: 5,                  // Maximum retry attempts
    initialDelay: 1000,             // Initial delay (1 second)
    maxDelay: 30000,                // Maximum delay (30 seconds)
    backoffFactor: 2,               // Exponential backoff multiplier
    retryableStatuses: [            // Status codes that trigger retry
      408,  // Request Timeout
      429,  // Too Many Requests
      500,  // Internal Server Error
      502,  // Bad Gateway
      503,  // Service Unavailable
      504,  // Gateway Timeout
    ],
    retryOnNetworkError: true,      // Retry on network failures
  },
});

// Automatically retries on failure with exponential backoff
const response = await client.get('/users');

Request Interceptors

import { HttpClient } from '@chittyos/http-client';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
});

// Add authentication interceptor
client.addRequestInterceptor((config) => {
  return {
    ...config,
    headers: {
      ...config.headers,
      'Authorization': `Bearer ${getToken()}`,
    },
  };
});

// Add logging interceptor
client.addRequestInterceptor(async (config) => {
  console.log(`[HTTP] ${config.method} ${config.url}`);
  return config;
});

// All requests will include the intercepted headers
await client.get('/users');

Response Interceptors

import { HttpClient } from '@chittyos/http-client';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
});

// Add response logging interceptor
client.addResponseInterceptor((response) => {
  console.log(`[HTTP] ${response.status} ${response.url}`);
  return response;
});

// Add response transformation interceptor
client.addResponseInterceptor(async (response) => {
  // Could modify response before returning
  return response;
});

await client.get('/users');

Error Interceptors

import { HttpClient } from '@chittyos/http-client';
import { NetworkError } from '@chittyos/types';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
});

// Add error logging interceptor
client.addErrorInterceptor((error) => {
  console.error('[HTTP Error]', error.message);
  return error;
});

// Add custom error transformation
client.addErrorInterceptor((error) => {
  if (error instanceof NetworkError && error.statusCode === 401) {
    // Handle authentication errors
    redirectToLogin();
  }
  return error;
});

try {
  await client.get('/protected');
} catch (error) {
  // Error has been processed by interceptors
}

Timeout Control

import { HttpClient } from '@chittyos/http-client';
import { TimeoutError } from '@chittyos/types';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
  timeout: 5000,  // 5 second default timeout
});

try {
  // Override timeout for specific request
  const response = await client.get('/slow-endpoint', {
    timeout: 30000,  // 30 second timeout
  });
} catch (error) {
  if (error instanceof TimeoutError) {
    console.error('Request timed out after', error.timeout, 'ms');
  }
}

Custom Headers

import { HttpClient } from '@chittyos/http-client';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
  headers: {
    'X-API-Key': 'your-api-key',
    'X-Client-Version': '1.0.0',
  },
});

// Override headers for specific request
await client.get('/users', {
  headers: {
    'X-Request-ID': 'unique-request-id',
  },
});

Error Handling

import { HttpClient } from '@chittyos/http-client';
import { NetworkError, TimeoutError } from '@chittyos/types';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
});

try {
  const response = await client.get('/users');
} catch (error) {
  if (error instanceof TimeoutError) {
    console.error('Request timed out:', error.timeout);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.statusCode, error.url);
  } else {
    console.error('Unknown error:', error);
  }
}

API Reference

HttpClient

Main HTTP client class with retry logic and interceptors.

Constructor Options:

  • baseURL?: string - Base URL for all requests
  • timeout?: number - Default timeout in milliseconds (default: 30000)
  • headers?: Record<string, string> - Default headers
  • retry?: RetryConfig - Retry configuration
  • requestInterceptors?: RequestInterceptor[] - Request interceptors
  • responseInterceptors?: ResponseInterceptor[] - Response interceptors
  • errorInterceptors?: ErrorInterceptor[] - Error interceptors

Methods:

  • get<T>(url, config?) - GET request
  • post<T>(url, body?, config?) - POST request
  • put<T>(url, body?, config?) - PUT request
  • patch<T>(url, body?, config?) - PATCH request
  • delete<T>(url, config?) - DELETE request
  • head(url, config?) - HEAD request
  • request<T>(config) - Generic request
  • addRequestInterceptor(interceptor) - Add request interceptor
  • addResponseInterceptor(interceptor) - Add response interceptor
  • addErrorInterceptor(interceptor) - Add error interceptor

createChittyOSHttpClient(config?)

Create HTTP client with ChittyOS defaults (User-Agent, retry logic, etc.).

createServiceHttpClient(service, baseURL, config?)

Create HTTP client for specific ChittyOS service with service identifier header.

Features

  • ✅ Type-safe HTTP requests with TypeScript
  • ✅ Automatic retry with exponential backoff
  • ✅ Timeout control with AbortController
  • ✅ Request/response/error interceptors
  • ✅ Configurable retry logic
  • ✅ Network error handling
  • ✅ JSON body serialization
  • ✅ ChittyOS integration (service headers, defaults)
  • ✅ Zero runtime dependencies (except @chittyos/types and @chittyos/config)

Package Size

~35KB (gzipped)

License

MIT