Installation

Install voca-http using npm:

npm install voca-http

Basic Usage

voca-http provides a simple and intuitive API for making HTTP requests. You can use it directly with the global methods:

1import { voca } from 'voca-http';
2
3// Basic usage with global fetch
4const posts = await voca.get('https://jsonplaceholder.typicode.com/posts');
5const post = await voca.post('https://jsonplaceholder.typicode.com/posts', { 
6  title: 'foo', 
7  body: 'bar', 
8  userId: 1 
9});

Configuration

For more advanced usage, create a configured instance with custom settings:

1// Create a configured instance
2const api = voca.create(fetch, {
3  baseUrl: 'https://api.example.com',
4  timeout: 5000,
5  retryCount: 3,
6  onResponse: async (response) => {
7    if (!response.ok) {
8      throw new Error(`HTTP Error: ${response.status}`);
9    }
10    return response.json();
11  },
12  onError: (error) => {
13    console.error('API Error:', error);
14    return Promise.reject(error);
15  }
16});
17
18// Use the configured instance
19const users = await api.get('/users');
20const newUser = await api.post('/users', { name: 'John Doe', email: 'john@example.com' });

The configuration object supports the following options:

  • baseUrl - Base URL for all requests
  • timeout - Request timeout in milliseconds
  • retryCount - Number of retry attempts for failed requests
  • onRequest - Function to modify request options
  • onResponse - Function to process successful responses
  • onError - Function to handle request errors
  • interceptors - Request and response interceptors

Interceptors

Interceptors allow you to modify requests before they are sent and responses before they are returned:

1// Add a request interceptor for authentication
2voca.config.addRequestInterceptor((options) => {
3  options.headers = {
4    ...options.headers,
5    'Authorization': 'Bearer your-token-here'
6  };
7  return options;
8});
9
10// Add a response interceptor for logging
11voca.config.addResponseInterceptor((response) => {
12  console.log(`Response from ${response.url}: ${response.status}`);
13  return response;
14});

Error Handling

voca-http provides several ways to handle errors:

Using try/catch

1try {
2  const data = await api.get('/some-endpoint');
3} catch (error) {
4  console.error('Request failed:', error.message);
5}

Using onError handler

The onError handler in the configuration object is called for any request error:

1const api = voca.create(fetch, {
2  onError: (error) => {
3    // Log the error
4    console.error('API Error:', error);
5    
6    // You can transform the error or return a default value
7    return Promise.reject(error);
8  }
9});

File Upload

voca-http provides built-in support for file uploads with progress tracking:

1// Upload a file with progress tracking
2const updateProgress = (percent) => {
3  console.log(`Upload progress: ${percent.toFixed(1)}%`);
4  progressBar.style.width = `${percent}%`;
5};
6
7const result = await voca.uploadFile(
8  'https://example.com/upload', 
9  fileObject,
10  { 'Authorization': 'Bearer your-token' },
11  updateProgress
12);

File Download

You can also download files with progress tracking:

1// Download a file with progress tracking
2const updateProgress = (percent) => {
3  console.log(`Download progress: ${percent.toFixed(1)}%`);
4  progressBar.style.width = `${percent}%`;
5};
6
7const fileData = await voca.downloadFile(
8  'https://example.com/files/document.pdf',
9  { 'Authorization': 'Bearer your-token' },
10  updateProgress
11);

Timeout & Retry

voca-http automatically handles request timeouts and retries:

1const api = voca.create(fetch, {
2  timeout: 5000,  // 5 seconds timeout
3  retryCount: 3   // Retry failed requests up to 3 times
4});

Requests that fail due to network issues or server errors will be automatically retried based on the configured retryCount. Requests that exceed the timeout will be aborted.