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

@gleissonneves/liz-api-client

v1.1.0

Published

Cliente HTTP baseado em fetch, com suporte a interceptadores, retry automático, timeout e tratamento de erros.

Readme

📡 API Client - JavaScript Fetch Wrapper

Uma biblioteca de cliente HTTP moderna e extensível, baseada em fetch, com suporte a interceptadores, retry automático, timeout configurável e tratamento de erros avançado.

✨ Recursos

✅ baseUrl configurável ✅ Timeout nativo por requisição ✅ Retry automático em erros de rede (configurável) ✅ Interceptadores (onRequest, onResponse, onError) ✅ Tratamento de erros com classe ApiError ✅ Parsing automático de JSON e Text ✅ Controle de query params em requisições GET ✅ Totalmente extensível para middlewares e caching

🚀 Instalação

🛠️ Uso básico

  1. Importação e Instância
npm install @gleissonneves/liz-api-client
import { Api } from "@gleissonneves/liz-api-client";

const api = new Api({
  baseUrl: 'https://api.meuservico.com',
  timeout: 10000, // Opcional (default: 15 segundos)
  maxRetries: 2,  // Opcional (default: 2 tentativas)
});
  1. Métodos Disponíveis
  • api.get(endpoint, queryParams = {}, config = {})
  • api.post(endpoint, body = {}, config = {})
  • api.put(endpoint, body = {}, config = {})
  • api.delete(endpoint, config = {})
  • api.setInterceptors({ request, response, error })

📚 Exemplos de uso

  1. Requisição GET com Query Params
const { data } = await api.get('/usuarios', { ativo: true });
console.log(data);
  1. Requisição POST com corpo de dados
await api.post('/login', { email: '[email protected]', senha: '123456' });
  1. Tratamento de Erros
try {
  const { data } = await api.get('/dados');
} catch (error) {
  if (error instanceof ApiError) {
    console.error('Erro de API', error.status, error.data);
  } else {
    console.error('Erro desconhecido', error);
  }
}

🔥 Interceptadores

Adicionando Interceptadores Globais

api.setInterceptors({
  request: async (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  response: async (response) => {
    // Você pode manipular a resposta aqui
    return response;
  },
  error: async (error) => {
    // Centralize o tratamento de erros aqui
    console.error('Interceptado erro:', error);
    throw error;
  }
});

⚙️ Configurações aceitas no construtor

| Propriedade | Tipo | Descrição | Default | |-------------|--------|---------------------------------------------|----------------------------------------| | baseUrl | string | URL base para todas as requisições | '' | | timeout | number | Tempo limite em ms para abortar requisição | 15000 | | maxRetries | number | Número máximo de tentativas em erro de rede | 2 | | headers | object | Cabeçalhos padrão | { 'Content-Type': 'application/json' } |

🧩 Classe de Erro: ApiError

Todos os erros de API são lançados como instâncias de ApiError.

Atributos disponíveis:

  • status: Código HTTP da resposta
  • data: Corpo da resposta (JSON ou texto)
  • response: Objeto Response original

🛡️ Roadmap Futuro

  • [] Suporte a cache de respostas (Cache-First)
  • [] Middlewares encadeáveis (use(middleware))
  • [] Retentativas inteligentes baseadas em erro (retryIf)
  • [] Upload progress (com onUploadProgress)
  • [] Caching com invalidation (stale-while-revalidate)