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

rivia-fetch

v1.0.0

Published

A simple and objective HTTP utility library for simplified fetch operations

Readme

Rivia Fetch JS

Uma biblioteca Javascript utilitária simples e objetiva para simplificar requisições HTTP usando fetch, com tratamento de erros aprimorado, lógica de retry e suporte a múltiplos tipos de conteúdo.

🚀 Características

  • Simples e Intuitivo: API clean com funções específicas para cada caso de uso
  • Retry Automático: Lógica inteligente de retry para erros de rede e servidor
  • Múltiplos Content-Types: Suporte nativo para JSON, Form Data, Text, Buffer e Images
  • Tratamento de Erros: Gerenciamento abrangente de erros HTTP e de rede
  • Logging Integrado: Sistema de logs usando rivia-logs

📦 Instalação

npm install rivia-fetch

🎯 Uso Rápido

Requisições Básicas

const { get, post, put, patch, del } = require('rivia-fetch');

// GET com parâmetros de query string
const users = await get('https://api.example.com/users', { 
  page: 1, 
  limit: 10 
});

// POST com dados JSON no body
const newUser = await post('https://api.example.com/users', {
  name: 'João Silva',
  email: '[email protected]'
});

// PUT para atualização completa com dados JSON no body
const updatedUser = await put('https://api.example.com/users/123', {
  name: 'João Santos',
  email: '[email protected]'
});

// PATCH para atualização parcial com dados JSON no body
const partialUpdate = await patch('https://api.example.com/users/123', {
  email: '[email protected]'
});

// DELETE
await del('https://api.example.com/users/123');

Diferentes Tipos de Resposta

const { fetchJson, fetchText, fetchImage, fetchBuffer } = require('rivia-fetch');

// Resposta JSON (padrão)
const data = await fetchJson('https://api.example.com/data');

// Resposta como texto
const html = await fetchText('https://example.com/page.html');

// Imagem como base64
const imageBase64 = await fetchImage('https://example.com/image.jpg');

// Buffer de dados binários
const buffer = await fetchBuffer('https://example.com/file.pdf');

Enviando Form Data

const { postForm } = require('rivia-fetch');

// Form data como objeto
const response1 = await postForm('https://api.example.com/upload', {
  username: 'joao',
  password: 'senha123'
});

// Form data nativo do browser/Node
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('description', 'Minha imagem');

const response2 = await postForm('https://api.example.com/upload', formData);

Cliente Configurável

const { createClient } = require('rivia-fetch');

// Cliente com configuração personalizada
const client = createClient({
  baseURL: 'https://api.example.com',
  headers: {
    'Authorization': 'Bearer token123',
    'X-API-Key': 'myapikey'
  },
  timeout: 15000,
  retries: 3,
  retryDelay: 2000
});

// Usar o cliente configurado
const response = await client.makeRequest('/users/profile', {
  method: 'GET'
});

const data = await response.json();

⚙️ Configurações Avançadas

Opções de Requisição

Todas as funções aceitam um objeto options como último parâmetro:

const options = {
  // Configuração do cliente
  clientConfig: {
    baseURL: 'https://api.example.com',
    headers: { 'Authorization': 'Bearer token' },
    timeout: 10000,
    retries: 2,
    retryDelay: 1500
  },
  
  // Opções específicas da requisição
  retries: 3,           // Sobrescreve a config do cliente
  headers: {            // Headers adicionais/sobrescrever
    'X-Custom': 'value'
  }
};

const data = await get('/users', { page: 1 }, {}, options);

Headers Personalizados

const { post } = require('rivia-fetch');

const customHeaders = {
  'Content-Type': 'application/xml',
  'Authorization': 'Bearer token123',
  'X-Custom-Header': 'valor'
};

const response = await post(
  'https://api.example.com/data',
  '<xml>data</xml>',
  customHeaders
);

Content-Types Suportados

const { CONTENT_TYPES } = require('rivia-fetch');

// Tipos disponíveis:
// CONTENT_TYPES.JSON                 → 'application/json'
// CONTENT_TYPES.FORM_DATA            → 'multipart/form-data'
// CONTENT_TYPES.URL_ENCODED          → 'application/x-www-form-urlencoded'
// CONTENT_TYPES.TEXT                 → 'text/plain'
// CONTENT_TYPES.HTML                 → 'text/html'
// CONTENT_TYPES.XML                  → 'application/xml'
// CONTENT_TYPES.OCTET_STREAM         → 'application/octet-stream'

🚨 Tratamento de Erros

A biblioteca lança erros HTTP apropriados que podem ser capturados:

const { get } = require('rivia-fetch');

try {
  const data = await get('https://api.example.com/protected');
} catch (error) {
  if (error.status === 401) {
    console.log('Não autorizado');
  } else if (error.status === 404) {
    console.log('Recurso não encontrado');
  } else if (error.status >= 500) {
    console.log('Erro do servidor');
  } else {
    console.log('Erro de rede:', error.message);
  }
}

📝 Logs

A biblioteca usa o rivia-logs para logging. Configure a variável de ambiente:

export LOGGER_NAME=minha-app

Os logs incluem:

  • Detalhes das requisições (URL, método, tentativas)
  • Respostas bem-sucedidas
  • Erros e tentativas de retry
  • Performance e timing

🧪 Exemplos Práticos

API REST Completa

const { createClient, get, post, put, del } = require('rivia-fetch');

class UserAPI {
  constructor(apiKey) {
    this.client = createClient({
      baseURL: 'https://api.myapp.com/v1',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      retries: 2
    });
  }

  async getUsers(page = 1, limit = 10) {
    return get('/users', { page, limit }, {}, {
      clientConfig: this.client.config
    });
  }

  async createUser(userData) {
    return post('/users', userData, {}, {
      clientConfig: this.client.config
    });
  }

  async updateUser(id, userData) {
    return put(`/users/${id}`, userData, {}, {
      clientConfig: this.client.config
    });
  }

  async deleteUser(id) {
    return del(`/users/${id}`, {}, {
      clientConfig: this.client.config
    });
  }
}

// Uso
const api = new UserAPI('meu-token-api');
const users = await api.getUsers();

Upload de Arquivos

const { postForm } = require('rivia-fetch');

async function uploadFile(file, description) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('description', description);
  formData.append('timestamp', Date.now());

  return postForm('https://api.example.com/upload', formData, {
    'X-Upload-Type': 'user-content'
  });
}

📊 Estrutura do Projeto

src/
├── core/
│   ├── client.js      # Cliente HTTP principal
│   └── api.js         # Funções da API pública
├── utils/
│   └── helpers.js     # Funções utilitárias
├── types/
│   └── index.js       # Constantes e tipos
└── index.js           # Ponto de entrada principal

🤝 Contribuindo

  1. Fork o projeto
  2. Crie uma branch para sua feature (git checkout -b feature/AmazingFeature)
  3. Commit suas mudanças (git commit -m 'Add some AmazingFeature')
  4. Push para a branch (git push origin feature/AmazingFeature)
  5. Abra um Pull Request

📄 Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.

🔗 Links