npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

axly

v1.0.27

Published

A powerful HTTP client library built on top of Axios with features like retry logic, progress tracking, request cancellation, and React integration.

Downloads

232

Readme

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: '[email protected]'
  },
  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!