UNPKG

@vepler/http-client

Version:

A flexible and extensible API service library for making HTTP requests with built-in authentication support for bearer tokens and API keys.

123 lines (103 loc) 4.23 kB
## 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 ```bash npm install @vepler/http-client ``` ### Usage ```typescript 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: 'john@example.com', }, { token: 'your-bearer-token', apiKey: 'your-api-key', }); // Make a PUT request const updatedUser = await api.put('users/123', { name: 'John Doe', email: 'john.doe@example.com', }, { 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 errors - `ClientError`: For 4xx series errors (client errors) - `ServerError`: For 5xx series errors (server errors) - `NetworkError`: For network connectivity issues - `AuthError`: For authentication failures (401, 403) - `TimeoutError`: For request timeouts - `RateLimitError`: 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 code - `statusText`: The HTTP status text - `endpoint`: The endpoint that was requested - `method`: The HTTP method used - `url`: The full URL that was requested - `data`: The response data from the server - `message`: A detailed error message Specialized error classes include additional properties: - `AuthError` includes `credentials` (with sensitive data redacted) - `RateLimitError` includes `retryAfter` (for retry-after header) - `ValidationError` includes `validationErrors` (field-level errors) #### Example Usage ```typescript 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.