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

axios-http-wrapper

v1.1.1

Published

HTTP class wrapper around axios for making api calls easier.

Downloads

6

Readme

Axios HTTP wrapper

Axios HTTP wrapper is a simple class wrapper around axios written in typescript that's made to generalize API calls for the whole project, to make API calls easier, and to make your code cleaner.

You can use this wrapper as you want but our advice is to create one file (or if you're using React, create a hook) where you will instantiate one generalized HttpClient class and configure your axios client as you want. And then reuse it in your services. HttpClient class is written as an abstract class, and if you want to use it, you have to extend it. You have to pass some props to instantiate this class.

Installation

To install and use this package run

yarn add axios-http-wrapper
npm install axios-http-wrapper

Props

HttpClient's super constructor need to take two parameters. httpClientConstructor and axios config.

httpClientConstructor

This object consists of three properties:

  • useHttps?: boolean - which is false by default. It's used by normalizeUrl function that's taking care of removing any duplicated slashes if you have any. And it will prepend an http:// or https:// to your baseUrl. If useHttps = true, normalizeUrl will prepend https:// to your baseURL and if it's false it will prepend http://
  • baseUrl: string - it's the base part of your API URL. It's generally an http://0.0.0.0:PORT or http://localhost:PORT if you're developing on a local environment or any other base URL if your API is published somewhere.
  • endpoint?: string - as the name says it's an endpoint, when you pass it the final product will look something like this: baseUrl/endpoint. If endpoint is changing a lot it shouldn't be passed as a prop to the instantiated http client class

baseUrl and endpoint are properties that you're passing just to instantiate your base http class.

config

It's just an AxiosRequestConfig object that doesn't have baseURL as a prop. You can check about this config more on the official documentation.

Usage

When you instantiate this class. You get access to get, post, put, patch and delete request. Every request is typed and every request has some props you need to pass, such as url and some props that are optional as data and config.

Here are definitions of all requests you can do:

// Model is a generic that's passed to a HttpClient class when you instanciate it.
get<ReturnType = Model>(url: string, config?: AxiosRequestConfig)

post<ReturnType = Model, DataType = ReturnType>(
  url: string,
  data?: DataType,
  config?: AxiosRequestConfig,
)

put<ReturnType = Model, DataType = ReturnType>(
  url: string,
  data?: DataType,
  config?: AxiosRequestConfig,
)

patch<ReturnType = Model, DataType = ReturnType>(
  url: string,
  data?: Partial<DataType>,
  config?: AxiosRequestConfig,
)

delete<ReturnType = Model>(url: string, config?: AxiosRequestConfig)

React example

If you're using React you can simplify the usage of this wrapper by creating some useHttpClient hook that can be reused for the whole project. For example:

// useHttpClient.ts
import { useMemo } from 'react';
import { HttpClient, HttpClientConstructor, HttpClientAxiosConfig } from 'axios-http-wrapper';

export function useHttpClient<T>(endpoint?: string) {
  // Use types for autocompletion.
  const httpClientConstructor: HttpClientConstructor = {
    useHttps: false, // it's false by default, but you can define it
    baseUrl: 'http://some.api.url',
    endpoint,
  }

  const config: HttpClientAxiosConfig<BaseModel> = {
    headers: {
      accept: 'application/json',
    };
  }

  class ClientService extends HttpClient<T> {
    constructor() {
      super(httpClientConstructor, config);

      // If you need to configure some axios interceptors, you can also do this here.
      this.client.interceptors.response.use(
        (response) => response,
        (error) => error,
      );
    }
  }

  return useMemo(() => new ClientService(), []);
}

And when you want to create some API calls, just call this hook and use instanciated service.

// useMakingApiCalls.ts

export function useMakingApiCalls() {
  const someService = useHttpClient<SomeModel>('/general-endpoint-for-this-service');

  // delete call is the same as get
  async function getApiCall() {
    try {
      const result = await someService.get<SomeModel>('/endpoint');
      // do something with the result
    } catch(e) {
      // do something with this error
    }
  }

  async function getApiCallWithParams(params: ParamType) {
    try {
      const result = await someService.get('/endpoint', { params });
      // do something with the result
    } catch(e) {
      // do something with this error
    }
  }

  // put and patch are the same as post call
  async function postApiCall(someData: DataType) {
    try {
      const result = await someService.post('/endpoint', someData);
      // do something with the result
    } catch(e) {
      // do something with this error
    }
  }

}

More general example

To use this you can create an http.ts file and inside define your http client class that's extending our, defined HttpClient class. For example:

// http.ts
import { HttpClient, HttpClientConstructor, HttpClientAxiosConfig } from 'axios-http-wrapper';

// Type it for autocomplete.
const httpClientConstructor: HttpClientConstructor = {
  useHttps: false, // it's false by default, but you can define it
  baseUrl: 'http://some.api.url',
}

const config: HttpClientAxiosConfig<BaseModel> = {
  headers: {
    accept: 'application/json',
  };
}

// HttpClient class can have some BaseModel passed as a generic.
export const MyHttpClient extends HttpClient<BaseModel> {
  constructor(private endpoint?: string) {
    super({
      useHttps: false, // it's false by default, but you can define it
      baseUrl: 'http://some.api.url',
      endpoint: this.endpoint,
    }, config);

    // If you need to configure some axios interceptors, you can also do this here.
    this.client.interceptors.response.use(
      (response) => response,
      (error) => error,
    );
  }
}

And then you can use this as

const someApiCalls = new MyHttpClient('/some-endpoint');

// delete call is the same as get
async function getApiCall() {
  try {
    const result = await someService.get<SomeModel>('/endpoint');
    // do something with the result
  } catch(e) {
    // do something with this error
  }
}

async function getApiCallWithParams(params: ParamType) {
  try {
    const result = await someService.get('/endpoint', { params });
    // do something with the result
  } catch(e) {
    // do something with this error
  }
}

// put and patch are the same as post call
async function postApiCall(someData: DataType) {
  try {
    const result = await someService.post('/endpoint', someData);
    // do something with the result
  } catch(e) {
    // do something with this error
  }
}

Special thanks to @vlaja for initiating the creation of this wrapper and special thanks to @mrkaza for simplifying the usage of this wrapper.