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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ktranish/hook

v1.0.4

Published

A lightweight HTTP client built on the Fetch API, designed for flexibility, configurability, lifecycle logging, and analytics.

Downloads

324

Readme

Hook

A lightweight HTTP client built on the Fetch API, designed for flexibility, configurability, lifecycle logging, and analytics.

About

Hook is a flexible HTTP library built directly on the Fetch API. It supports global and local configurations, lifecycle logging, analytics, and all HTTP methods, making it an ideal choice for applications that demand granular control over network requests. With TypeScript compatibility, Hook ensures type safety and an enhanced developer experience.

Features

  • 🌐 Flexible HTTP Methods: Shortcuts like hook.get, hook.post, hook.del, etc.
  • 🛡️ Global Configuration: Define default headers, mode, and credentials.
  • 🔄 Content-Type Detection: Automatically parses JSON, text, binary, and more.
  • 📈 Lifecycle Logging: Hook into request, response, and error events.
  • 📊 Built-in Analytics: Monitor total requests, response times, success rates, and errors.

Getting Started

Installation

Install Hook via your preferred package manager:

# npm
npm install @ktranish/hook

# yarn
yarn add @ktranish/hook

# pnpm
pnpm add @ktranish/hook

Usage

1. Basic GET Request

import hook from '@ktranish/hook';

const fetchData = async () => {
  const data = await hook.get('https://api.example.com/resource');
  console.log(data);
};

2. POST Request with Data

const createResource = async () => {
  const data = await hook.post('https://api.example.com/resource', { name: 'New Resource' });
  console.log(data);
};

3. Global Configuration

Configure global headers, credentials, or other fetch options:

import { configureGlobal } from '@ktranish/hook';

configureGlobal({
  headers: { Authorization: 'Bearer your-token' },
  credentials: 'include',
});

await hook.get('https://api.example.com/resource');

4. Local Overrides

Override global configurations for specific requests:

await hook.get('https://api.example.com/resource', {
  headers: { 'Custom-Header': 'CustomValue' }, // Overrides global headers
  cache: 'no-cache', // Specific to this request
});

5. Lifecycle Logging

Global Logging

Configure global loggers to track all HTTP requests:

import { configureLogger } from '@ktranish/hook';

configureLogger({
  onRequest: (url, options) => console.log(`[Global Request] ${url}`, options),
  onResponse: (url, response) => console.log(`[Global Response] ${url}`, response),
  onError: (url, error) => console.error(`[Global Error] ${url}`, error),
});

await hook.get('https://api.example.com/resource'); // Automatically logged

Local Logging

Override global logging with a local logger:

const localLogger = {
  onRequest: (url, options) => console.log(`[Local Request] ${url}`, options),
  onResponse: (url, response) => console.log(`[Local Response] ${url}`, response),
  onError: (url, error) => console.error(`[Local Error] ${url}`, error),
};

await hook.post(
  'https://api.example.com/resource',
  { name: 'New Resource' },
  { logger: localLogger }
);

6. Analytics

Hook comes with built-in analytics to monitor your HTTP activity.

Retrieve Analytics

import { getAnalytics } from '@ktranish/hook';

const analytics = getAnalytics();
console.log('Analytics:', analytics);

Reset Analytics

import { resetAnalytics } from '@ktranish/hook';

resetAnalytics();
console.log('Analytics reset.');

Sample Analytics Data

{
  "totalRequests": 10,
  "requestMethods": {
    "GET": 5,
    "POST": 3,
    "DELETE": 2
  },
  "averageResponseTime": 120.5,
  "successfulRequests": 8,
  "failedRequests": 2,
  "errorCodes": {
    "404": 1,
    "500": 1
  },
  "responseTimes": [100, 120, 130, 140, 110]
}

7. Custom Fetch Options

Hook supports all valid Fetch API options:

await hook.get('https://api.example.com/resource', {
  cache: 'no-cache',
  redirect: 'manual',
  integrity: 'sha256-abcdef...',
});

API Reference

HTTP Method Shortcuts

  • hook.get<T>(url, options)
  • hook.post<T>(url, data, options)
  • hook.put<T>(url, data, options)
  • hook.del<T>(url, options) (alias for DELETE)
  • hook.patch<T>(url, data, options)
  • hook.head<T>(url, options)
  • hook.options<T>(url, options)

Parameters

| Parameter | Type | Description | | --------- | ------------- | --------------------------------------------------- | | url | string | The URL to send the HTTP request to. | | options | RequestInit | Options for fetch (e.g., headers, body, mode). | | data | any | The data to send with POST, PUT, or PATCH requests. |

Testing

Hook includes a robust test suite to ensure reliability. Run the tests with:

npm test

Example Test

import hook, { configureGlobal } from './hook';

describe('Hook Tests', () => {
  it('should perform a GET request successfully', async () => {
    const data = await hook.get('https://api.example.com/resource');
    expect(data).toBeDefined();
  });
});

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature-name).
  3. Commit your changes (git commit -m 'Add new feature').
  4. Push to the branch (git push origin feature-name).
  5. Open a Pull Request.

License

This project is licensed under the MIT License.