Socket
Socket
Sign inDemoInstall

xior

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xior

Axios similiar API request library but based on fetch


Version published
Weekly downloads
2.2K
decreased by-25.3%
Maintainers
1
Weekly downloads
 
Created
Source

Build npm version minzipped size tree shaking typescript dependency license

Xior

An axios similar API request library but use fetch, and more.

Features:

  • 🫡 Similiar axios.create / axios.interceptors.request.use / axios.interceptors.response.use / .get/post/put/patch/delete/head/options
  • 🔥 Use fetch
  • 🚀 Lightweight ~6KB, Gzip ~2.6KB
  • 🤙 Support timeout and cancel request
  • 👊 Unit tests
  • 💪 100% Write in TypeScript
  • ❗️❗️❗️WIP 🥷 Plugins support: error retry, cache, repeat requests filter plugins 😎

Install

npm i xior

Getting Started

import xior from 'xior';

const http = xior.create({ baseURL: 'https://exmaple.com', timeout: 120 * 1000 });

http.interceptors.request.use((config) => {
  // do something
  return config;
});

http.interceptors.response.use((result) => {
  const { config, response, data } = result;
  // do something
  return result;
});

// GET
async function getList() {
  const { data } = await http.get('/list', { params: { page: 1, perPage: 20 } });
  return data;
}

// POST
async function create() {
  const { data } = await http.post(
    '/create',
    { name: 'test', desc: 'foobar..foobar' },
    { params: { redirect: '/list' } }
  );
  return data;
}

Usage

GET / POST

import xior from 'xior';

const instance = xior.create({});

await instance.get('http://httpbin.org', {
  params: {
    a: 1,
    b: 2,
  },
});

await instance.post('http://httpbin.org', {
  a: 1,
  b: 2,
});

URL encode support nested objects

In xior, URI encoded strings default use lite encode, means if your params is nested object, it will be [object object]:

import xior from 'xior';

const instance = xior.create({});
instance.get('http://httpbin.org', {
  params: {
    a: 1,
    b: {
      c: 2,
    },
  },
});

The url will be like: http://httpbin.org?a=1&b=[object object], to support nested objects url encoded, use qs's stringify module:

import xior from 'xior';
// @ts-ignore
import stringify from 'qs/lib/stringify';

const instance = xior.create({
  encode: (params: Record<string, any>) => stringify(params, {}),
});
instance.get('http://httpbin.org', {
  params: {
    a: 1,
    b: {
      c: 2,
    },
  },
});

// http://httpbin.org?a=1&b[c]=2

Upload data

Not like axios, xior doesn't support upload progess or download progress.

Use FormData to upload files.

import xior from 'xior';

const instance = xior.create();

const formData = new FormData();

formData.append('file', fileObject);
formData.append('filed1', 'val1');
formData.append('filed2', 'val2');

instance.post('/upload', formData).then((res) => {
  console.log(res.data);
});

Timeout

import xior from 'xior';

const instance = xior.create({
  timeout: 120 * 1000,
});

await instance.post(
  'http://httpbin.org',
  {
    a: 1,
    b: 2,
  },
  {
    timeout: 60 * 1000, // override default timeout 120 * 1000
  }
);

Cancel request

import xior from 'xior';
const instance = xior.create();

const controller = new AbortController();

xiorInstance.get('http://httpbin.org', { signal: controller.signal }).then((res) => {
  console.log(res.data);
});

class CancelRequestError extends Error {}
controller.abort(new CancelRequestError()); // abort request with custom error

xior.interceptors.request.use

import xior, { merge as deepMerge } from 'xior';

const instance = xior.create();
instance.interceptors.request.use((config) => {
  return deepMerge(config, {
    headers: {
      token: localStorage.getItem('token') || '',
    },
  });
});

xior.interceptors.response.use

import xior, { merge as deepMerge } from 'xior';

const instance = xior.create();
instance.interceptors.response.use(
  (res) => {
    const { data, request, response } = res;
    console.log(request, resposne, data);
    return res;
  },
  function onRejected(error) {
    throw error;
  }
);

stream

if the options responseType is responseType: 'stream' | 'document' | 'arraybuffer' | 'blob', then xior will just return the original response: { response }, you can do anthing with response you like:

import xior, { merge as deepMerge } from 'xior';
const instance = xior.create({
  baseURL: 'http://httpbin.org',
});

instance.get('/stream', { responseType: 'stream' }).then(({ response }) => {
  // `response` is the original response, like fetch('/stream').then(response => { console.log(response)})
});

Use plugins

❗️❗️❗️ WIP (Work in Progress) ❗️❗️❗️

import xior from 'xior';
import xiorCachePlugin from 'xior/lib/plugins/cache';
import xiorErrorRetryPlugin from 'xior/lib/plugins/error-retry';
import xiorRepeatRequestsFilterPlugin from 'xior/lib/plugins/repeat-requests-filter';

const instance = xior.create();

instance.plugins.use(xiorCachePlugin());
instance.plugins.use(xiorErrorRetryPlugin());
instance.plugins.use(xiorAvoidRepeatRequestsPlugin());

Custom plugin

❗️❗️❗️ WIP (Work in Progress) ❗️❗️❗️

import xior from 'xior';

const instance = xior.create();
instance.plugins.use(async (request, response, error) => {
  const inRequestPhase = !response;
  const inResponsePhase = Boolean(response);
  const isError = Boolean(error);

  if (isError) {
    //
  }
  if (inRequestPhase) {
    //
  } else if (inResponsePhase) {
    //
  }
});

FAQ

  • Is xior 100% compatiable with axios? No
  • How to upload files? Use FormData
  • How to show upload progress like axios? Doesn't support.
  • What about response of 'stream' | 'document' | 'arraybuffer' | 'blob' ? Use responseType: 'stream' | 'document' | 'arraybuffer' | 'blob', will return original { response }
  • More: Anything else? create new issues let me know!

Keywords

FAQs

Package last updated on 20 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc