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 🙏

© 2026 – Pkg Stats / Ryan Hefner

losi-network-manager

v1.0.3

Published

A robust wrapper around losi-tiny-http with advanced features

Readme

losi-network-manager

A robust HTTP client wrapper around losi-tiny-http with enterprise-grade features.

🎯 Features

  • Smart Caching - In-memory and persistent storage (localStorage/sessionStorage)
  • Request Queue & Offline Mode - Automatic queueing with concurrency control
  • Automatic Token Refresh - Built-in auth middleware with token refresh
  • Retry Strategy - Inherited from losi-tiny-http with exponential backoff
  • Batch Requests - Execute multiple requests in parallel
  • React Hooks - useRequest hook for easy integration

📦 Installation

npm install losi-network-manager

🚀 Quick Start

import { createNetworkManager } from 'losi-network-manager';

const api = createNetworkManager({
  baseURL: 'https://api.example.com',
  cache: { ttl: 60000, storage: 'memory' },
  queue: { maxConcurrent: 5 },
  retry: { attempts: 3, backoff: 'exponential', delay: 500 }
});

const response = await api.get('/users/1');
console.log(response.data);

🔧 Configuration

Cache Configuration

const api = createNetworkManager({
  cache: {
    ttl: 60000, // Time to live in milliseconds
    storage: 'memory' | 'local' | 'session'
  }
});

Queue Configuration

const api = createNetworkManager({
  queue: {
    maxConcurrent: 5 // Maximum concurrent requests
  }
});

Auth Configuration

const api = createNetworkManager({
  auth: {
    token: () => localStorage.getItem('token') || '',
    refreshToken: async () => {
      const response = await fetch('/auth/refresh');
      const { token } = await response.json();
      localStorage.setItem('token', token);
      return token;
    },
    onRefreshSuccess: (newToken) => console.log('Token refreshed'),
    onRefreshFailure: (error) => console.error('Refresh failed', error)
  }
});

📚 Usage Examples

Basic Requests

// GET
const user = await api.get('/users/1');

// POST
const newUser = await api.post('/users', { name: 'John' });

// PUT
const updated = await api.put('/users/1', { name: 'Jane' });

// PATCH
const patched = await api.patch('/users/1', { email: '[email protected]' });

// DELETE
await api.delete('/users/1');

Caching

// First request - fetches from server
const data1 = await api.get('/posts/1');

// Second request - returns from cache (instant)
const data2 = await api.get('/posts/1');

// Skip cache
const fresh = await api.get('/posts/1', { skipCache: true });

Batch Requests

const results = await api.batch([
  () => api.get('/users/1'),
  () => api.get('/users/2'),
  () => api.get('/users/3')
]);

results.forEach((result, i) => {
  if (result.status === 'fulfilled') {
    console.log(`User ${i + 1}:`, result.value.data);
  } else {
    console.error(`User ${i + 1} failed:`, result.reason);
  }
});

React Hook

import { useRequest } from 'losi-network-manager';

function UserProfile({ userId }) {
  const { data, error, loading, refetch } = useRequest(
    api,
    userId ? `user-${userId}` : null,
    (client) => client.get(`/users/${userId}`)
  );

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  
  return (
    <div>
      <h1>{data?.name}</h1>
      <button onClick={refetch}>Refresh</button>
    </div>
  );
}

🎨 Advanced Features

Priority Requests

// High priority request (processed first in queue)
await api.get('/critical-data', { priority: 'high' });

// Normal priority (default)
await api.get('/data', { priority: 'normal' });

// Low priority
await api.get('/analytics', { priority: 'low' });

Offline Mode

The queue automatically detects offline/online status and queues requests when offline, then flushes them when back online.

🔥 Advanced Features

Retry with Jitter

Prevent thundering herd problem with jitter:

const api = createNetworkManager({
  retry: {
    attempts: 3,
    backoff: 'exponential',
    delay: 100,
    jitter: true, // Add randomness to retry delays
    maxDelay: 2000,
    shouldRetry: (error, attempt) => {
      // Custom retry logic
      return error.response?.status >= 500;
    }
  }
});

Request Deduplication

Prevent duplicate in-flight requests:

const api = createNetworkManager({
  deduplication: true
});

// These two requests will only make ONE network call
const [result1, result2] = await Promise.all([
  api.get('/users/1'),
  api.get('/users/1') // Reuses the first request's promise
]);

// Check in-flight requests
console.log(api.getInFlightCount());

Metrics Tracking

Track request performance and success rates:

const api = createNetworkManager({
  metrics: true
});

// Make some requests...
await api.get('/users/1');
await api.post('/users', { name: 'John' });

// Get metrics
const metrics = api.getMetrics();
console.log('Total Requests:', metrics.totalRequests);
console.log('Success Rate:', metrics.successRate + '%');
console.log('Average Duration:', metrics.averageDuration + 'ms');
console.log('Requests by Method:', metrics.requestsByMethod);
console.log('Requests by Status:', metrics.requestsByStatus);

// Clear metrics
api.clearMetrics();

📄 License

ISC

🤝 Contributing

Contributions welcome! This package wraps losi-tiny-http.