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

eleghttp

v0.11.6

Published

A TypeScript library for object-oriented HTTP communication

Readme

🌐 ElegHTTP

Uma biblioteca de requisições HTTP orientada a objetos para TypeScript.
Flexível, extensível e com suporte a interceptação, autenticação, monitoramento de download e muito mais.


📦 Instalação

npm install eleghttp
# ou
yarn add eleghttp

🔧 Importação

import { BaseApi, Methods, Abstracts, Contracts } from 'eleghttp'

🧱 Estrutura do Projeto

src/
├── abstracts/           # Classes abstratas reutilizáveis
├── api/                 # Core da biblioteca (BaseApi)
├── contracts/           # Interfaces (tipagens e contratos)
├── examples/            # Exemplos de uso
├── methods/             # Métodos HTTP (Get, Post, etc)
├── package.json
├── tsconfig.json
├── README.md

🚀 Uso Básico

Crie uma classe para cada requisição estendendo BaseApi e passando o método HTTP desejado:

import { BaseApi, Methods } from 'eleghttp'

class GetUserApi extends BaseApi {
  constructor(userId: string) {
    super()

    this.setMethod(new Methods.Get(`https://api.example.com/users/${userId}`))
  }

  async run() {
    return await this.execute()
  }
}

🧪 Exemplo de uso

const user = await new GetUserApi('123').run()
console.log(user.name)

📡 Métodos HTTP Suportados

Disponíveis no namespace Methods:

new Methods.Get(uri)
new Methods.Post(uri, data)
new Methods.Put(uri, data)
new Methods.Delete(uri)
new Methods.Patch(uri, data)
new Methods.Options(uri)
new Methods.Head(uri)
new Methods.Connect(uri)
new Methods.Trace(uri)

🧠 Uso Avançado

Você pode estender BaseApi e customizar:

  • Headers personalizados
  • Hooks antes e depois da requisição
  • Monitoramento de download
  • Tratamento de erros com classes reutilizáveis
import { BaseApi, Methods, Abstracts } from 'eleghttp'

class DownloadFileApi extends BaseApi {
  constructor(fileId: string, token: string) {
    super()

    this.setMethod(new Methods.Get(`https://api.example.com/files/${fileId}`))
      .setHeaders({
        Authorization: `Bearer ${token}`,
        Accept: 'application/octet-stream',
      })
      .setMonitor({
        onDownloadProgress: (received, total) => {
          console.log(`Download: ${received} / ${total}`)
        },
      })
      .setHooks({
        beforeRequest: () => console.log('Iniciando...'),
        afterRequest: (res) => console.log('Finalizado', res.status),
      })
      .setErrorHandler(new Abstracts.BaseErrorHandler())
  }

  async run(): Promise<Blob> {
    return await this.execute()
  }
}

✅ Funcionalidades

| Recurso | Suporte | |------------------------------|---------| | fetch nativo | ✅ | | Padrão orientado a objetos | ✅ | | Requisições genéricas | ✅ | | Monitoramento de download | ✅ | | Interceptadores de execução | ✅ | | Headers personalizados | ✅ | | Tratamento de erro customizável | ✅ | | Token JWT ou outro tipo de auth | ✅ |


📐 Contratos (Interfaces)

Disponíveis via Contracts.

IFetchMethod

interface IFetchMethod {
  getMethod(): string
  getUri(): string
  getData(): any
}

IRequestHook

interface IRequestHook {
  beforeRequest?: () => void | Promise<void>
  afterRequest?: (response: Response) => void | Promise<void>
}

IDownloadMonitor

interface IDownloadMonitor {
  onDownloadProgress?: (loaded: number, total?: number) => void
}

IErrorHandler

interface IErrorHandler {
  handleError(error: unknown): void
}

🧱 Classes Abstratas

BaseErrorHandler

abstract class BaseErrorHandler implements IErrorHandler {
  abstract handleError(error: unknown): void
}

Exemplo:

class MyHandler extends Abstracts.BaseErrorHandler {
  handleError(error: unknown): void {
    console.error('Erro capturado:', error)
  }
}

🧪 Exemplo Completo

import { BaseApi, Methods, Contracts, Abstracts } from 'ohttp'

class GetUserData extends BaseApi {
  constructor(token: string) {
    super()

    this.setMethod(new Methods.Get('https://api.example.com/user/data'))
      .setHeaders({ Authorization: `Bearer ${token}` })
      .setHooks({
        beforeRequest: () => console.log('Preparando...'),
        afterRequest: () => console.log('Finalizado'),
      })
      .setErrorHandler(new class extends Abstracts.BaseErrorHandler {
        handleError(err: unknown): void {
          console.warn('Erro:', err)
        }
      })
  }

  async run() {
    return await this.execute()
  }
}

const data = await new GetUserData('your_token').run()
console.log(data)

🛠 Contribuindo

  1. Faça um fork
  2. Crie uma branch (feat/minha-funcionalidade)
  3. Faça commit das alterações
  4. Envie um PR

📄 Licença

MIT License © 2025