axly
TypeScript icon, indicating that this package has built-in type declarations

1.0.27 • Public • Published

Axly 🪁

Axly is a powerful and flexible HTTP client library built on top of Axios. It provides a streamlined interface for making API requests with additional features like:

  • Dynamic request configurations
  • Request cancellation
  • Retry logic
  • Progress tracking for uploads and downloads
  • Easy integration with React, Next.js, and Node.js applications

Table of Contents

  1. Installation
  2. Features
  3. Usage
  1. API Reference
  1. Examples
  1. Contributing
  2. License

Installation

Install Axly using npm or bun:

bun add axly

or

npm install axly

Features

  • Dynamic Request Options: Customize each request with flexible configurations.
  • Request Cancellation: Cancel requests to prevent race conditions or unnecessary network calls.
  • Retry Logic: Automatically retry failed requests with configurable attempts.
  • Progress Tracking: Monitor upload and download progress for files and data streams.
  • Interceptors: Globally handle request and response transformations and errors.
  • TypeScript Support: Fully typed for an enhanced developer experience.
  • React.js, Node.js and Next.js Ready: Designed for seamless integration with modern frameworks.

Usage

Basic Usage

Start by configuring Axly with your base URL and other settings:

import { setAxiosConfig } from 'axly';

setAxiosConfig({
  baseURL: 'https://api.example.com',
  token: "user's-jwt-auth-token",
  defaultHeaders: {
    'Custom-Header': 'value'
  }
});

Then make a request:

import { makeRequest } from 'axly';

const fetchData = async () => {
  try {
    const response = await makeRequest({
      method: 'GET',
      url: '/api/data'
    });
    console.log(response.data);
  } catch (error) {
    console.error('Request failed:', error);
  }
};

React.js and Next.js Integration

Use the useAxios hook to manage state and requests in React components:

import React, { useEffect } from 'react';
import { useAxios } from 'axly';

const App = () => {
  const { makeRequest, isLoading, uploadProgress, downloadProgress } =
    useAxios();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await makeRequest({
          method: 'GET',
          url: '/todos/1'
        });
        console.log(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [makeRequest]);

  return (
    <div>
      {isLoading ?
        <p>Loading...</p>
      : <p>Data loaded!</p>}
      <p>Upload Progress: {uploadProgress}%</p>
      <p>Download Progress: {downloadProgress}%</p>
    </div>
  );
};

export default App;

Node.js Usage

Axly can be used in Node.js for server-side requests:

import { makeRequest, setAxiosConfig } from 'axly';

setAxiosConfig({
  baseURL: 'https://api.example.com'
});

const fetchData = async () => {
  try {
    const response = await makeRequest({
      method: 'GET',
      url: '/data'
    });

    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

fetchData();

API Reference

Configuration

setAxiosConfig(config)

Configures global settings for Axly.

setAxiosConfig({
  baseURL: 'https://api.example.com',
  token: 'your-auth-token',
  REQUEST_HEADER_AUTH_KEY: 'Authorization',
  TOKEN_TYPE: 'Bearer ',
  defaultHeaders: {
    'Custom-Header': 'value'
  },
  interceptors: {
    request: (config) => {
      console.log('Request sent:', config);
      return config;
    },
    response: (response) => {
      console.log('Response received:', response);
      return response;
    }
  }
});

makeRequest

Make HTTP requests with dynamic configurations.

  • Parameters: options (RequestOptions) – Configuration options for the request.
  • Returns: Promise<AxiosResponse<ApiResponse<T>>>.

useAxios Hook

A React hook that provides an interface to make HTTP requests and track their state.

  • Returns:
    • makeRequest: Function to make requests.
    • isLoading: Boolean indicating loading state.
    • uploadProgress: Upload progress percentage.
    • downloadProgress: Download progress percentage.

Examples

GET Request

const response = await makeRequest({
  method: 'GET',
  url: '/users',
  params: { page: 1 }
});
console.log(response.data);

POST Request with Data

const response = await makeRequest({
  method: 'POST',
  url: '/users',
  data: {
    name: 'John Doe',
    email: 'john@example.com'
  },
  contentType: 'application/json'
});
console.log(response.data);

File Upload with Progress

const { makeRequest, uploadProgress } = useAxios();

const handleFileUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file);

  await makeRequest({
    method: 'POST',
    url: '/upload',
    data: formData,
    contentType: 'multipart/form-data',
    onUploadProgress: (progress) => {
      console.log(`Upload Progress: ${progress}%`);
    }
  });
};

Custom Interceptors

setAxiosConfig({
  interceptors: {
    request: (config) => {
      console.log('Request sent:', config);
      return config;
    },
    response: (response) => {
      console.log('Response received:', response);
      return response;
    },
    requestError: (error) => {
      console.error('Request error:', error);
      return Promise.reject(error);
    },
    responseError: (error) => {
      console.error('Response error:', error);
      return Promise.reject(error);
    }
  }
});

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/your-feature).
  3. Commit your changes (git commit -am 'Add new feature').
  4. Push to the branch (git push origin feature/your-feature).
  5. Open a Pull Request.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Acknowledgments

Made with ❤️ by Harshal Katakiya. Feel free to reach out if you have any questions or need support!

Package Sidebar

Install

npm i axly

Weekly Downloads

232

Version

1.0.27

License

MIT

Unpacked Size

19.2 kB

Total Files

16

Last publish

Collaborators

  • harshalkatakiya