reqforge
v0.15.0
Published
A lightweight, flexible HTTP client library with request interception, automatic retry, and logging capabilities, designed for modern web applications.
Downloads
1,939
Maintainers
Readme
ReqForge
A lightweight, flexible HTTP client library with request interception, automatic retry, and logging capabilities, designed for modern web applications.
Installation
npm install reqforgeQuick Start
const { request, interceptor } = require('reqforge');
// Add a request interceptor
const reqInterceptor = interceptor.createRequestInterceptor();
reqInterceptor.use((config) => {
console.log('Request:', config.url);
return config;
});
// Make a request
request.get('/users')
.then(res => res.json())
.then(data => console.log(data));Examples
See the examples directory for more usage examples:
- basic.js - Basic GET and POST requests
- auth.js - Authentication flow
- retry.js - Retry with exponential backoff
API Reference
Request Methods
The request module provides:
sendRequest(endpoint, data, options)- Generic request methodget(endpoint, options)- GET requestpost(endpoint, data, options)- POST requestput(endpoint, data, options)- PUT requestdel(endpoint, options)- DELETE request
Configuration
The config module provides:
getBaseURL()- Get the base URL for API requestsAPI_VERSION- Current API versiondefaultConfig- Default configuration objectmergeConfig(customConfig)- Merge custom configuration with defaults
DebugLogger
The DebugLogger class provides:
log(message)- Log a messageinfo(message)- Log an info messagewarn(message)- Log a warning messageerror(message)- Log an error messagedebug(message, data)- Log debug message with optional data (only when debug mode enabled)enableDebug()- Enable debug mode
Authentication
The auth module provides:
login(username, password)- Login and store tokenlogout()- Logout and clear tokengetToken()- Get current auth tokensetToken(token)- Set auth token manuallyisAuthenticated()- Check if authenticated
Error Handling
The errors module provides:
ReqForgeError- Base error classNetworkError- Network request failuresTimeoutError- Request timeout errorsAuthError- Authentication failuresValidationError- Validation errorsErrorCodes- Error code constantscreateErrorFromResponse(response)- Create error from HTTP response
Retry Mechanism
The retry module provides:
withRetry(fn, options)- Execute function with automatic retrycalculateBackoff(attempt, baseDelay, maxDelay)- Calculate exponential backoff delay
Options for withRetry:
maxRetries(default: 3) - Maximum number of retry attemptsdelay(default: 1000) - Initial delay in millisecondsbackoff(default: 2) - Backoff multipliershouldRetry(error)- Function to determine if retry should occur
Interceptors
The interceptor module provides request and response interception:
createRequestInterceptor()- Create request interceptor managercreateResponseInterceptor()- Create response interceptor manager
InterceptorManager Methods
use(fulfilled, rejected)- Add interceptor handlereject(id)- Remove interceptor handlerclear()- Clear all handlersforEach(data)- Process data through all handlers
Caching
The cache module provides:
MemoryCache- In-memory cache with TTL supportget(key)- Get cached valueset(key, value, ttl)- Set cached value with optional TTLhas(key)- Check if key existsdelete(key)- Remove cached entryclear()- Clear all entriessize()- Get cache size
createCacheKey(url, params)- Generate cache key from URL and params
Utilities
The utils module provides:
buildURL(baseURL, params)- Build URL with query parametersserializeQuery(obj)- Serialize object to query stringparseQuery(queryString)- Parse query string to objectdeepMerge(target, source)- Deep merge objectsisPlainObject(value)- Check if value is a plain objectdelay(ms)- Delay execution
TypeScript Support
TypeScript type definitions are included. Import types:
import { request, config, Logger } from 'reqforge';Testing
npm testChangelog
See CHANGELOG.md for version history.
License
MIT
