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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@asaidimu/network-client

v1.0.0

Published

A lightweight, type-safe HTTP client for browser environments

Downloads

77

Readme

TypeScript Network Client

A flexible and powerful TypeScript HTTP client with middleware support, customizable request/response handling, and comprehensive type safety.

Features

  • 🚀 Full TypeScript support with comprehensive type definitions
  • ⚡️ Promise-based API with async/await
  • 🔄 Middleware system for request/response interceptors
  • ⏱️ Configurable timeout handling
  • 🎯 Custom response handlers
  • 🔍 Detailed error handling
  • 📝 Request ID tracking
  • 🔒 Automatic content type handling

Installation

npm install ts-network-client
# or
yarn add ts-network-client
# or
pnpm add ts-network-client

Quick Start

import createNetworkClient from 'ts-network-client';

// Create a client instance
const client = createNetworkClient({
  baseUrl: 'https://api.example.com',
  defaultHeaders: {
    'Authorization': 'Bearer your-token'
  },
  defaultTimeout: 5000
});

// Make requests
async function fetchUsers() {
  const response = await client.get<User[]>('/users');
  
  if (response.success) {
    console.log(response.data);
  } else {
    console.error(response.error);
  }
}

Configuration

The client can be configured with various options:

interface NetworkClientConfig {
  baseUrl: string;
  defaultHeaders?: Record<string, string>;
  defaultTimeout?: number;
  middleware?: Middleware[];
  responseHandler?: <T>(response: Response) => Promise<T>;
}

Making Requests

The client supports all standard HTTP methods:

// GET request
const getData = await client.get<ResponseType>('/endpoint');

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

// PUT request with options
const putData = await client.put<ResponseType>('/endpoint', body, {
  headers: { 'Custom-Header': 'value' },
  timeout: 3000
});

// DELETE request
const deleteData = await client.delete<ResponseType>('/endpoint');

Response Structure

All requests return a typed Response object:

interface Response<T> {
  data?: T;
  error?: ApiError;
  success: boolean;
  status?: number;
  headers?: Headers;
}

interface ApiError {
  message: string;
  status?: number;
  details?: unknown;
}

Middleware System

The middleware system allows you to intercept and modify requests and responses:

const loggingMiddleware: Middleware = {
  beforeRequest: async (context) => {
    console.log(`Request ${context.requestId} starting:`, {
      method: context.method,
      url: context.url
    });
    return context;
  },
  afterResponse: async (context) => {
    console.log(`Request ${context.requestId} completed:`, {
      status: context.response.status
    });
    return context;
  }
};

const client = createNetworkClient({
  baseUrl: 'https://api.example.com',
  middleware: [loggingMiddleware]
});

Custom Response Handlers

You can provide custom response handlers at both the client and request level:

// Client-level custom handler
const client = createNetworkClient({
  baseUrl: 'https://api.example.com',
  responseHandler: async (response) => {
    const data = await response.json();
    return data.results; // Transform response structure
  }
});

// Request-level custom handler
const response = await client.get('/endpoint', {
  responseHandler: async (response) => {
    const text = await response.text();
    return JSON.parse(text).customField;
  }
});

TypeScript Support

The client is fully typed and provides excellent TypeScript support:

interface User {
  id: number;
  name: string;
  email: string;
}

// Response will be typed as Response<User[]>
const users = await client.get<User[]>('/users');

// TypeScript will ensure the body matches the expected type
const newUser = await client.post<User>('/users', {
  name: 'John Doe',
  email: '[email protected]'
});

Error Handling

The client provides detailed error information:

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

if (!response.success) {
  console.error({
    message: response.error?.message,
    status: response.error?.status,
    details: response.error?.details
  });
  return;
}

// TypeScript knows response.data is User[] here
const users = response.data;

License

View LICENSE.md