Skip to content

Spicy-Sparks/Pantera-http

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

66 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

An HTTP request client that provides an axios like interface over top of fetch. Super lightweight. Supports interceptors and multiple instances.

Features

  • Make fetch requests with a simplified API
  • Supports the Promise API
  • Support multiple instances with default options
  • Intercept request and response
  • Automatic transforms for JSON and blob data
  • Automatic data object serialization to multipart/form-data, application/json and x-www-form-urlencoded body encodings
  • Automatic URL encoding with query string parameters
  • Support to basic auth and credentials

Installing

Using npm:

npm install pantera-http

Using yarn:

yarn add pantera-http

Basic usage

Creating a request

import pantera from 'pantera-http'

pantera.request({
  method: 'get',
  url: 'https://myapplication.com/api/user',
  params: {
    ID: 12345
  },
  responseType: 'json',
  headers: {
    Authorization: 'Bearer myToken',
    'Content-Type': 'application/json'
  }
})
.then(function (response) {
  // handle success
  const { data, config } = response
  console.log(data, config)
})
.catch(function (error) {
  // handle error
  const { response, config } = error
  console.log(error)
})
.then(function () {
  // always executed
})

Shortcuts for GET, POST, PUT, PATCH, PUT, OPTIONS, DELETE requests.

import pantera from 'pantera-http'

pantera.get('https://myapplication.com/api/user', {
  params: {
    ID: 12345
  },
  responseType: 'json'
})

pantera.post('https://myapplication.com/api/form', {
  body: {
    formField: 'value'
  },
  responseType: 'json',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

Creating multiple instances

It is possible to create multiple instances for different situations or across multiple APIs. Each instance can have a common base URL that will be applied to all requests, default headers, a common responseType, a common extraConfig or a common authentication. In general, the specified default configuration will be added to each request.

import { Pantera } from 'pantera-http'

const simpleClient = new Pantera({
  baseUrl: 'https://myapplication.com/api',
  responseType: 'json'
})

const response = await simpleClient.request('/user', {
  method: 'get',
  params: {
    ID: 1234
  }
})

// or
const response = await simpleClient.get('/user', {
  params: {
    ID: 1234
  }
})

const complexClient = new Pantera({
  baseUrl: 'https://myapplication.com/api',
  responseType: 'json',
  credentials: true,
  auth: {
    username: 'myUsername',
    password: 'myPassword'
  },
  headers: {
    'Content-Type': 'application/json',
    'X-Common-Header': 'myValue',
    'Authorization': 'Bearer myToken'
  },
  extraConfig: {
    variableForInterceptors: 'complexApi'
  }
})

const response = await complexClient.request({
  url: '/user',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  }
})

Using async/await

Pantera fully supports async/await syntax.

import pantera from 'pantera-http'

try {
  const response = await pantera.get('https://myapplication.com/api/json-response', {
    responseType: 'json',
    params: {
      myQueryStringParameter: 'value'
    }
  })
  // handle success
  const { data, config } = response
  console.log(data, config)
}
catch (error) {
  // handle error
  console.log(error)
}

Response encoding

The response is automatically parsed into JSON, Blob or plain text, depending on the responseType.

import pantera from 'pantera-http'

pantera.get('https://myapplication.com/api/json-response', {
  responseType: 'json'
})

pantera.get('https://myapplication.com/api/index.html', {
  responseType: 'text'
})

pantera.get('https://myapplication.com/api/myfile', {
  responseType: 'blob'
})

All your files and folders are presented as a tree in the file explorer. You can switch from one to another by clicking a file in the tree.

Intercepting requests and responses

You can intercept requests or responses before they are handled by then or catch.

import { Pantera } from 'pantera-http'

const myClient = new Pantera({
  baseUrl: 'https://myapplication.com/api',
  responseType: 'json'
})

myClient.interceptors.request.use((config) => {
  // Do something before request is sent

  if(!config.headers)
    config.headers = {}

  config.headers.Authorization = 'Bearer myToken'
  return config
})

myClient.interceptors.response.use(
  (response) => {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { config, data } = response
    return response;
  },
  (error) => {
    // Any status codes that falls outside the range of 2xx cause this function to 	trigger
    // Do something with response error

    if (err.status === 401) {
      const refreshResponse = await refreshToken()
      err.config.headers.Authorization = `Bearer ${refreshResponse.newToken}`
      return myClient.request(err.config)
    }

    return Promise.reject(error)
  }
)

Multiple concurrent requests

Since Pantera is based on Promise, you can send multiple requests that will be executed at the same time and read all their responses at the end using Promise.all, or any other Promise API.

import pantera from 'pantera-http'

Promise.all([
  pantera.get('https://myapplication.com/api/index.html', {
    responseType: 'text'
  })
])
.then(([ response1, response2 ]) => {
  // handle success
  const { data1, config1 } = response1
  console.log(data1, config1);
})
.catch((errors) => {
  // handle error
  console.log(errors)
})

Support to auth and credentials

Pantera supports basic auth and credentials. credentials can be include (or true), omit (or false), same-origin.

import pantera from 'pantera-http'

pantera.get('https://myapplication.com/api/json-response', {
  responseType: 'json',
  credentials: true,
  auth: {
    username: 'myUsername',
    password: 'myPassword'
  }
})

Extra data for config

In case you need to get custom attributes in your interceptor or response, you can append it in extraConfig.

import { Pantera } from 'pantera-http'

const myClient = new Pantera({
  baseUrl: 'https://myapplication.com/api'
})

myClient.interceptors.request.use((config) => {
  if(config.extraConfig?.myCustomAttribute) {
    console.log('Received myCustomAttribute')
  }
  return config
})

myClient.post('/form', {
  body: {
    formField: 'value'
  },
  extraConfig: {
    myCustomAttribute: true
  }
})

Credits

Pantera is heavily inspired by axios and is built on top of the fetch API. Pantera is developed and mantained by Spicy Sparks and widely used in eSound Music

License

MIT

About

An HTTP request client that provides an axios like interface over top of node-fetch. Super lightweight. Supports interceptors and multiple instances.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published