A lightweight HTTP client built on the Fetch API, designed for flexibility, configurability, lifecycle logging, and analytics.
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.
- π 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.
Install Hook via your preferred package manager:
# npm
npm install @ktranish/hook
# yarn
yarn add @ktranish/hook
# pnpm
pnpm add @ktranish/hook
import hook from '@ktranish/hook';
const fetchData = async () => {
const data = await hook.get('https://api.example.com/resource');
console.log(data);
};
const createResource = async () => {
const data = await hook.post('https://api.example.com/resource', { name: 'New Resource' });
console.log(data);
};
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');
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
});
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 }
);
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]
}
Hook supports all valid Fetch API options:
await hook.get('https://api.example.com/resource', {
cache: 'no-cache',
redirect: 'manual',
integrity: 'sha256-abcdef...',
});
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)
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. |
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();
});
});
Contributions are welcome! To contribute:
- Fork the repository.
- Create a feature branch (
git checkout -b feature-name
). - Commit your changes (
git commit -m 'Add new feature'
). - Push to the branch (
git push origin feature-name
). - Open a Pull Request.
This project is licensed under the MIT License.