@vepler/http-client
v1.0.2
Published
A flexible and extensible API service library for making HTTP requests with built-in authentication support for bearer tokens and API keys.
Downloads
385
Maintainers
Readme
Vepler Core HTTP Wrapper
A flexible and extensible API service library for making HTTP requests with built-in authentication support for bearer tokens and API keys.
Installation
npm install @vepler/http-clientUsage
import ApiService from '@vepler/http-client';
// Create an instance of the API service
const api = ApiService.create({
host: 'https://api.example.com',
timeout: 5000,
logLevel: 'info',
headers: {
'Content-Type': 'application/json',
},
});
// Make a GET request
const response = await api.get('users', '123', {
token: 'your-bearer-token',
apiKey: 'your-api-key',
});
// Make a POST request
const newUser = await api.post('users', {
name: 'John Doe',
email: '[email protected]',
}, {
token: 'your-bearer-token',
apiKey: 'your-api-key',
});
// Make a PUT request
const updatedUser = await api.put('users/123', {
name: 'John Doe',
email: '[email protected]',
}, {
token: 'your-bearer-token',
apiKey: 'your-api-key',
});
// Make a DELETE request
await api.delete('users', '123', {
token: 'your-bearer-token',
apiKey: 'your-api-key',
});Configuration
The create method of the ApiService accepts an options object with the following properties:
- host (required): The base URL of the API.
- timeout (optional): The request timeout in milliseconds. Default is 3000.
- logLevel (optional): The log level for the API service. Default is 'info'.
- headers (optional): Additional headers to be included in all requests.
Authentication
The API service supports authentication using bearer tokens and API keys. You can pass the token and apiKey properties as part of the queryParams object when making requests.
- token: The bearer token for authentication.
- apiKey: The API key for authentication.
Interceptors
The API service includes built-in request and response interceptors for logging and error handling. You can customize or extend these interceptors by modifying the logRequest, interceptorResponseSuccess, and interceptorResponseError functions.
Error Handling
The API service includes a comprehensive error handling system that provides detailed information about errors. All HTTP errors are converted to typed error classes that extend the base HttpError class, making it easy to handle different types of errors in your application.
Available Error Classes
HttpError: The base error class for all HTTP errorsClientError: For 4xx series errors (client errors)ServerError: For 5xx series errors (server errors)NetworkError: For network connectivity issuesAuthError: For authentication failures (401, 403)TimeoutError: For request timeoutsRateLimitError: For rate limiting errors (429)ValidationError: For validation errors (400 with details)
Error Properties
All error classes include the following properties:
status: The HTTP status codestatusText: The HTTP status textendpoint: The endpoint that was requestedmethod: The HTTP method usedurl: The full URL that was requesteddata: The response data from the servermessage: A detailed error message
Specialized error classes include additional properties:
AuthErrorincludescredentials(with sensitive data redacted)RateLimitErrorincludesretryAfter(for retry-after header)ValidationErrorincludesvalidationErrors(field-level errors)
Example Usage
import ApiService, { HttpError, AuthError } from '@vepler/http-client';
try {
const result = await api.get('users', '123');
} catch (error) {
if (error instanceof AuthError) {
// Handle authentication errors
console.error(`Auth failed: ${error.status} ${error.message}`);
// Redirect to login page
} else if (error instanceof HttpError) {
// Handle other HTTP errors
console.error(`API Error: ${error.status} ${error.message}`);
} else {
// Handle other errors
console.error(`Unknown error: ${error.message}`);
}
}The error handling system also automatically redacts sensitive information like API keys and tokens, while still providing enough context for debugging.
License
This project is licensed under the MIT License.
