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

@authuser/http-core

v1.0.2

Published

Módulo base para gestionar peticiones HTTP con arquitectura por middlewares, soportando:

Readme

@authuser/http-core

Módulo base para gestionar peticiones HTTP con arquitectura por middlewares, soportando:

  • Retry automático
  • Caché persistente de respuestas
  • Deduplicación de peticiones simultáneas
  • Rate limiting
  • Métricas personalizadas
  • Sesión opcional para autenticación

Instalación

npm install @authuser/http-core

Constructor del HttpService

El constructor recibe un objeto HttpServiceOptions con las siguientes propiedades:

| Atributo | Tipo | Obligatorio | Descripción | | ------------- | --------------------- | ----------- | ---------------------------------------------------------------------------------------- | | client | HttpClientPort | ✅ Sí | Cliente HTTP que implementa request(). Ej: AxiosHttpClient. | | session | SessionManagerPort? | ❌ No | (Opcional) Gestor de sesión JWT (token/refresh/logout). Por defecto: NoSessionManager. | | config | CoreConfig? | ❌ No | (Opcional) Configuración global del servicio HTTP (ver más abajo). | | cache | CachePort? | ❌ No | (Opcional) Implementación para persistir la caché. Por defecto: MemoryCache. | | logLevel | LogLevel[]? | ❌ No | (Opcional) Niveles de log activos: 'error', 'warn', 'info', 'debug'. | | middlewares | Middleware[]? | ❌ No | (Opcional) Middlewares personalizados que se ejecutan antes de los internos. |

Configuración (CoreConfig)

| Propiedad | Tipo | Obligatorio | Descripción | | --------------- | -------------------------------------------------- | ----------- | ---------------------------------------------------------------------------- | | baseUrl | string | ✅ Sí | URL base para peticiones relativas. | | retry | RetryConfig? | ❌ No | Configura reintentos automáticos (ver más abajo). Por defecto deshabilitado. | | cache | { enabled: boolean; ttlMs: number; maxEntries? } | ❌ No | Activa caché por TTL. También se puede habilitar por petición. | | rateLimit | { requests: number; perMs: number } | ❌ No | Define número máximo de peticiones por intervalo (tokens/intervalo). | | metrics | MetricsPort | ❌ No | Callbacks para medir rendimiento: onRequestStart? y onRequestEnd?. | | commonHeaders | Record<string, string> | ❌ No | Cabeceras comunes aplicadas a todas las peticiones (solo URLs no externas). |

RetryConfig

type RetryConfig = {
	enabled?: boolean; // activar/desactivar retry
	maxAttempts?: number; // número máximo de reintentos
	delay?: number; // retardo base en ms
	backoff?: 'linear' | 'exponential' | 'fixed'; // tipo de backoff
	skipOnStatusCode?: number[]; // evitar retry si status es uno de estos
	skipOnEndpoint?: string[]; // evitar retry si URL contiene uno de estos strings
	onRetry?: (retryCount: number, error: AxiosError, config: any) => void; // callback opcional
};

Uso básico

import { HttpService } from '@authuser/http-core';
import { AxiosHttpClient } from '@authuser/http-core/infrastructure';
import { LocalSessionManager } from '@authuser/http-core/infrastructure';

const http = new HttpService({
	client: new AxiosHttpClient(),
	session: new LocalSessionManager(), // opcional
	config: {
		baseUrl: 'https://api.example.com',
		retry: {
			enabled: true,
			maxAttempts: 2,
			delay: 300,
			backoff: 'exponential',
			skipOnEndpoint: ['/auth/login'],
			skipOnStatusCode: [401, 429],
		},
		cache: { enabled: true, ttlMs: 60_000 },
		rateLimit: { requests: 10, perMs: 1_000 },
		metrics: {
			onRequestStart: (key) => console.log('start:', key),
			onRequestEnd: (key, time, success) => console.log('end:', key, time, success),
		},
	},
});

Ejemplo de petición

const response = await http.request({
	url: '/users',
	method: 'GET',
	cache: true, // puede forzar cache local
	requiresAuth: true, // solo si necesitas token de sesión
});

Middlewares personalizados

Puedes inyectar middlewares personalizados para extender el comportamiento del servicio HTTP. Los middlewares personalizados se ejecutan antes de los middlewares internos.

Definición de un Middleware

type Middleware<T = unknown, B = unknown> = (
	req: HttpRequest<B>,
	next: () => Promise<HttpResponse<T>>
) => Promise<HttpResponse<T>>;

Ejemplo: Inyectar headers dinámicamente

import { HttpService, Middleware } from '@authuser/http-core';

const customHeaderMiddleware: Middleware = async (req, next) => {
	// Modificar el request antes de continuar
	req.headers = {
		...req.headers,
		'X-Request-ID': crypto.randomUUID(),
		'X-Timestamp': Date.now().toString(),
	};
	return next();
};

const http = new HttpService({
	client: new AxiosHttpClient(),
	middlewares: [customHeaderMiddleware],
});

Ejemplo: Logging personalizado

const loggingMiddleware: Middleware = async (req, next) => {
	console.log(`→ [${req.method}] ${req.url}`);
	const start = Date.now();

	try {
		const response = await next();
		const duration = Date.now() - start;
		console.log(`← [${response.status}] ${req.url} (${duration}ms)`);
		return response;
	} catch (error) {
		const duration = Date.now() - start;
		console.error(`✗ [ERROR] ${req.url} (${duration}ms)`, error);
		throw error;
	}
};

Ejemplo: Transformación de respuestas

const transformMiddleware: Middleware = async (req, next) => {
	const response = await next();

	// Transformar la respuesta antes de devolverla
	return {
		...response,
		data: {
			...response.data,
			timestamp: new Date().toISOString(),
		},
	};
};

Combinando múltiples middlewares

const http = new HttpService({
	client: new AxiosHttpClient(),
	middlewares: [
		loggingMiddleware, // Se ejecuta primero
		customHeaderMiddleware, // Después este
		transformMiddleware, // Y finalmente este
	],
});

Middlewares incluidos (orden de ejecución)

Los middlewares se ejecutan en el siguiente orden:

  1. Middlewares personalizados (en el orden que los pasaste)
  2. persistenceMw: Gestiona persistencia offline-first (si está configurado)
  3. cacheMw: Busca en caché antes de hacer la petición y almacena la respuesta si cache está activo
  4. dedupeMw: Evita peticiones duplicadas simultáneas (deduplicación)
  5. rateMw: Limita el número de peticiones por intervalo usando token bucket
  6. metricsMw: Mide el tiempo de cada petición y ejecuta callbacks onRequestStart y onRequestEnd
  7. httpMw: Ejecuta el cliente HTTP real (Axios, Fetch...) con lógica de retry y refresh token automático

Tipos principales

HttpRequest<TBody>

interface HttpRequest<TBody = unknown> {
	readonly url: string;
	readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
	readonly headers?: Record<string, string>;
	readonly query?: Record<string, string | number | boolean>;
	readonly body?: TBody;
	readonly requiresAuth?: boolean; // Incluye automáticamente el token JWT
	readonly cache?: boolean; // Forzar uso de caché para esta petición
	readonly cacheTtlMs?: number; // TTL específico para esta petición
	readonly signal?: AbortSignal; // Cancelación de peticiones
}

HttpResponse<T>

interface HttpResponse<T = unknown> {
	status: number;
	data: T;
	headers: Record<string, string>;
}

HttpError

class HttpError extends Error {
	status: number;
	request: HttpRequest;
	response?: unknown;
}

Características avanzadas

  • Refresh Token automático: Si una petición devuelve 401 y tiene requiresAuth: true, intenta refrescar el token automáticamente una vez.
  • URLs externas: Si la URL comienza con http:// o https://, no se aplican las commonHeaders.
  • Logging por niveles: Configura logLevel en el constructor para ver logs de error, warn, info, o debug.
  • Cancelación de peticiones: Usa AbortController y pasa el signal en el HttpRequest.

Arquitectura

Este módulo sigue una arquitectura hexagonal:

  • Domain: Puertos (interfaces) que definen contratos.
  • Application: Lógica de negocio (HttpService, Config).
  • Infrastructure: Adaptadores concretos (AxiosHttpClient, CacheManager, LocalSessionManager).

Este módulo es la base para @authuser/http-react y @authuser/http-react-native.