Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

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 - npm Package Compare versions

Comparing version 0.0.2 to 0.0.3

lib/plugins/cache.d.ts

4

dist/index.esm.d.ts

@@ -57,3 +57,5 @@ export { merge } from 'ts-deepmerge';

};
request<T>(url: string, options?: XiorRequestConfig): Promise<{
request<T>(options?: XiorRequestConfig & {
url: string;
}): Promise<{
data: T;

@@ -60,0 +62,0 @@ request: XiorRequestConfig;

@@ -1,1 +0,1 @@

import{merge as e}from"ts-deepmerge";export{merge}from"ts-deepmerge";function t(e,t){let r=new globalThis.AbortController;function n(e){r.abort(e),o()}let s=[];for(let t of e){if((null==t?void 0:t.aborted)===!0){n(t.reason);break}if((null==t?void 0:t.addEventListener)!=null){let e=()=>{n(t.reason)};s.push(()=>{(null==t?void 0:t.removeEventListener)!=null&&t.removeEventListener("abort",e)}),t.addEventListener("abort",e)}}function o(){s.forEach(e=>{e()}),null==t||t()}let a=r.signal;return a.clear=o,a}function r(e,t=!0){let r=[];return"object"==typeof e&&null!==e&&Object.keys(e).map(n=>(function(e,t,r,n){let s=e[t];if(null===s||s instanceof Function)return;let o=n?encodeURIComponent(t)+"="+encodeURIComponent(s):t+"="+s;r.push(o)})(e,n,r,t)),r.join("&")}function n(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}class s extends Error{}class o extends Error{constructor(e,t,r){super(e),this.request=t,this.response=r}}function a(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}let u="application/x-www-form-urlencoded",l="application/json";function c(e){return d.apply(this,arguments)}function d(){var t;return t=function*(t){let n=t.encode||r,s=!1!==t.encodeURI,o=t.method?t.method.toUpperCase():"GET",a=t.url||"",c=a,d=t.data,p=!1,h=(null==t?void 0:t.headers)||{};if(d&&!(d instanceof FormData)){let r="";if(null==t?void 0:t.headers){let e=Object.keys(t.headers).find(e=>"content-type"===e.toLowerCase());e&&(r=t.headers[e])}if(r||(r="GET"===o||"HEAD"===o?u:l,h["Content-Type"]=r),r===u&&("object"==typeof d||t.params)){p=!0;let r=n(e(d||{},t.params||{}),s);r&&(a=a.includes("?")?a+=`&${r}`:`${a}?${r}`),d=null}else r===l&&(d=JSON.stringify(d))}return!p&&t.params&&Object.keys(t.params).length>0&&(a=a.includes("?")?a+=`&${n(t.params,s)}`:`${a}?${n(t.params,s)}`),i({},t,{data:d,url:c,_url:a,method:o,headers:h})},(d=function(){var e=this,r=arguments;return new Promise(function(n,s){var o=t.apply(e,r);function i(e){a(o,n,s,i,u,"next",e)}function u(e){a(o,n,s,i,u,"throw",e)}i(void 0)})}).apply(this,arguments)}function p(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function h(){return(h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}class f{static create(e){return new f(e)}get interceptors(){return{request:{use:(e,t)=>{this.requestInterceptors.push(e)}},response:{use:(e,t)=>{this.responseInterceptors.push({fn:e,onRejected:t})}}}}request(r,a){var i,u=this;return(i=function*(){var i;let l;let c=e(u.config||{},a||{},{url:r});for(let e of u.requestInterceptors)c=yield e(c);let{url:d,method:p,headers:f,timeout:v,signal:y,data:m}=c,T=function(e,t){if(null==e)return{};var r,n,s={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(s[r]=e[r]);return s}(c,["url","method","headers","timeout","signal","data"]),b=[];if(v){let e=new AbortController;l=setTimeout(()=>{e.abort(new s(`timeout of ${v}ms exceeded`))},v),b.push(e.signal)}y&&b.push(y);let g=b[0];b.length>1&&(g=t(b,()=>{clearTimeout(l)}));let x=c._url||d||r;c.baseURL&&!n(x)&&(x=(c.baseURL.endsWith("/")?c.baseURL:c.baseURL+"/")+(x.startsWith("/")?x.slice(1):x));let E=yield fetch(x,h({body:["HEAD","GET"].includes(c.method||"GET")?void 0:m},T,{signal:g,method:p,headers:f}));if(l&&clearTimeout(l),null==g||null==(i=g.clear)||i.call(g),!E.ok){let e;try{(e=yield E.text())&&(e=JSON.parse(e))}catch(e){}let t=new o(E.status?`Request failed with status code ${E.status}`:"Network error",c,{response:E,data:e,config:c,status:E.status,statusText:E.statusText,headers:E.headers});for(let e of u.responseInterceptors)e.onRejected&&(yield e.onRejected(t));throw t}if("HEAD"===c.method)return{data:void 0,request:c,config:c,response:E,headers:E.headers,status:E.status,statusText:E.statusText};if(!c.responseType||"json"===c.responseType||"text"===c.responseType){let e;try{e={data:yield E.text()};try{e.data&&"text"!==c.responseType&&(e.data=JSON.parse(e.data))}catch(e){}}catch(t){e={data:void 0}}let t={data:e.data,request:c,response:E};for(let e of u.responseInterceptors)t=yield e.fn(t);return{data:t.data,request:c,config:c,response:E,headers:E.headers,status:E.status,statusText:E.statusText}}return{data:void 0,request:c,config:c,response:E,headers:E.headers,status:E.status,statusText:E.statusText}},function(){var e=this,t=arguments;return new Promise(function(r,n){var s=i.apply(e,t);function o(e){p(s,r,n,o,a,"next",e)}function a(e){p(s,r,n,o,a,"throw",e)}o(void 0)})})()}createGetHandler(e){return(t,r)=>this.request(t,r?h({},r,{method:e,url:t}):{method:e,url:t})}createPostHandler(e){return(t,r,n)=>this.request(t,n?h({},n,{method:e,url:t,data:r}):{method:e,url:t,data:r})}get(e,t){return this.createGetHandler("GET")(e,t)}head(e,t){return this.createGetHandler("HEAD")(e,t)}post(e,t,r){return this.createPostHandler("POST")(e,t,r)}put(e,t,r){return this.createPostHandler("PUT")(e,t,r)}patch(e,t,r){return this.createPostHandler("PATCH")(e,t,r)}delete(e,t,r){return this.createPostHandler("DELETE")(e,t,r)}options(e,t,r){return this.createPostHandler("OPTIONS")(e,t,r)}constructor(e){this.requestInterceptors=[c],this.responseInterceptors=[],this.config=e}}export{o as XiorError,s as XiorTimeoutError,t as anySignal,f as default,r as encode,n as isAbsoluteURL,f as xior};
import{merge as e}from"ts-deepmerge";export{merge}from"ts-deepmerge";function t(e,t){let r=new globalThis.AbortController;function n(e){r.abort(e),o()}let s=[];for(let t of e){if((null==t?void 0:t.aborted)===!0){n(t.reason);break}if((null==t?void 0:t.addEventListener)!=null){let e=()=>{n(t.reason)};s.push(()=>{(null==t?void 0:t.removeEventListener)!=null&&t.removeEventListener("abort",e)}),t.addEventListener("abort",e)}}function o(){s.forEach(e=>{e()}),null==t||t()}let a=r.signal;return a.clear=o,a}function r(e,t=!0){let r=[];return"object"==typeof e&&null!==e&&Object.keys(e).map(n=>(function(e,t,r,n){let s=e[t];if(null===s||s instanceof Function)return;let o=n?encodeURIComponent(t)+"="+encodeURIComponent(s):t+"="+s;r.push(o)})(e,n,r,t)),r.join("&")}function n(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}class s extends Error{}class o extends Error{constructor(e,t,r){super(e),this.request=t,this.response=r}}function a(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}let u="application/x-www-form-urlencoded",l="application/json";function c(e){return d.apply(this,arguments)}function d(){var t;return t=function*(t){let n=t.encode||r,s=!1!==t.encodeURI,o=t.method?t.method.toUpperCase():"GET",a=t.url||"",c=a,d=t.data,p=!1,h=(null==t?void 0:t.headers)||{};if(d&&!(d instanceof FormData)){let r="";if(null==t?void 0:t.headers){let e=Object.keys(t.headers).find(e=>"content-type"===e.toLowerCase());e&&(r=t.headers[e])}if(r||(r="GET"===o||"HEAD"===o?u:l,h["Content-Type"]=r),r===u&&("object"==typeof d||t.params)){p=!0;let r=n(e(d||{},t.params||{}),s);r&&(a=a.includes("?")?a+=`&${r}`:`${a}?${r}`),d=null}else r===l&&(d=JSON.stringify(d))}return!p&&t.params&&Object.keys(t.params).length>0&&(a=a.includes("?")?a+=`&${n(t.params,s)}`:`${a}?${n(t.params,s)}`),i({},t,{data:d,url:c,_url:a,method:o,headers:h})},(d=function(){var e=this,r=arguments;return new Promise(function(n,s){var o=t.apply(e,r);function i(e){a(o,n,s,i,u,"next",e)}function u(e){a(o,n,s,i,u,"throw",e)}i(void 0)})}).apply(this,arguments)}function p(e,t,r,n,s,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function h(){return(h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}class f{static create(e){return new f(e)}get interceptors(){return{request:{use:(e,t)=>{this.requestInterceptors.push(e)}},response:{use:(e,t)=>{this.responseInterceptors.push({fn:e,onRejected:t})}}}}request(r){var a,i=this;return(a=function*(){var a;let u;let l=e(i.config||{},r||{});for(let e of i.requestInterceptors)l=yield e(l);let{url:c,method:d,headers:p,timeout:f,signal:v,data:y}=l,m=function(e,t){if(null==e)return{};var r,n,s={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(s[r]=e[r]);return s}(l,["url","method","headers","timeout","signal","data"]),T=[];if(f){let e=new AbortController;u=setTimeout(()=>{e.abort(new s(`timeout of ${f}ms exceeded`))},f),T.push(e.signal)}v&&T.push(v);let b=T[0];T.length>1&&(b=t(T,()=>{clearTimeout(u)}));let g=l._url||c||"";l.baseURL&&!n(g)&&(g=(l.baseURL.endsWith("/")?l.baseURL:l.baseURL+"/")+(g.startsWith("/")?g.slice(1):g));let x=yield fetch(g,h({body:["HEAD","GET"].includes(l.method||"GET")?void 0:y},m,{signal:b,method:d,headers:p}));if(u&&clearTimeout(u),null==b||null==(a=b.clear)||a.call(b),!x.ok){let e;try{(e=yield x.text())&&(e=JSON.parse(e))}catch(e){}let t=new o(x.status?`Request failed with status code ${x.status}`:"Network error",l,{response:x,data:e,config:l,status:x.status,statusText:x.statusText,headers:x.headers});for(let e of i.responseInterceptors)e.onRejected&&(yield e.onRejected(t));throw t}if("HEAD"===l.method)return{data:void 0,request:l,config:l,response:x,headers:x.headers,status:x.status,statusText:x.statusText};if(!l.responseType||"json"===l.responseType||"text"===l.responseType){let e;try{e={data:yield x.text()};try{e.data&&"text"!==l.responseType&&(e.data=JSON.parse(e.data))}catch(e){}}catch(t){e={data:void 0}}let t={data:e.data,request:l,response:x};for(let e of i.responseInterceptors)t=yield e.fn(t);return{data:t.data,request:l,config:l,response:x,headers:x.headers,status:x.status,statusText:x.statusText}}return{data:void 0,request:l,config:l,response:x,headers:x.headers,status:x.status,statusText:x.statusText}},function(){var e=this,t=arguments;return new Promise(function(r,n){var s=a.apply(e,t);function o(e){p(s,r,n,o,i,"next",e)}function i(e){p(s,r,n,o,i,"throw",e)}o(void 0)})})()}createGetHandler(e){return(t,r)=>this.request(r?h({},r,{method:e,url:t}):{method:e,url:t})}createPostHandler(e){return(t,r,n)=>this.request(n?h({},n,{method:e,url:t,data:r}):{method:e,url:t,data:r})}get(e,t){return this.createGetHandler("GET")(e,t)}head(e,t){return this.createGetHandler("HEAD")(e,t)}post(e,t,r){return this.createPostHandler("POST")(e,t,r)}put(e,t,r){return this.createPostHandler("PUT")(e,t,r)}patch(e,t,r){return this.createPostHandler("PATCH")(e,t,r)}delete(e,t,r){return this.createPostHandler("DELETE")(e,t,r)}options(e,t,r){return this.createPostHandler("OPTIONS")(e,t,r)}constructor(e){this.requestInterceptors=[c],this.responseInterceptors=[],this.config=e}}export{o as XiorError,s as XiorTimeoutError,t as anySignal,f as default,r as encode,n as isAbsoluteURL,f as xior};

@@ -57,3 +57,5 @@ export { merge } from 'ts-deepmerge';

};
request<T>(url: string, options?: XiorRequestConfig): Promise<{
request<T>(options?: XiorRequestConfig & {
url: string;
}): Promise<{
data: T;

@@ -60,0 +62,0 @@ request: XiorRequestConfig;

@@ -28,3 +28,5 @@ import { XiorRequestConfig } from './types';

};
request<T>(url: string, options?: XiorRequestConfig): Promise<{
request<T>(options?: XiorRequestConfig & {
url: string;
}): Promise<{
data: T;

@@ -31,0 +33,0 @@ request: XiorRequestConfig;

@@ -51,6 +51,6 @@ "use strict";

}
request(url, options) {
request(options) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
let requestObj = (0, utils_1.merge)(this.config || {}, options || {}, { url });
let requestObj = (0, utils_1.merge)(this.config || {}, options || {});
for (const item of this.requestInterceptors) {

@@ -79,3 +79,3 @@ requestObj = yield item(requestObj);

}
let finalURL = requestObj._url || _url || url;
let finalURL = requestObj._url || _url || '';
if (requestObj.baseURL && !(0, utils_1.isAbsoluteURL)(finalURL)) {

@@ -184,3 +184,3 @@ const baseURL = requestObj.baseURL.endsWith('/')

return (url, options) => {
return this.request(url, options ? Object.assign(Object.assign({}, options), { method, url }) : { method, url });
return this.request(options ? Object.assign(Object.assign({}, options), { method, url }) : { method, url });
};

@@ -190,3 +190,3 @@ }

return (url, data, options) => {
return this.request(url, options ? Object.assign(Object.assign({}, options), { method, url, data }) : { method, url, data });
return this.request(options ? Object.assign(Object.assign({}, options), { method, url, data }) : { method, url, data });
};

@@ -193,0 +193,0 @@ }

{
"name": "xior",
"version": "0.0.2",
"description": "axios similiar API request lib but based on fetch",
"version": "0.0.3",
"description": "Axios similiar API request library but based on fetch",
"repository": "suhaotian/xior",

@@ -44,3 +44,4 @@ "bugs": "https://github.com/suhaotian/xior/issues",

"@types/qs": "^6.9.11",
"bunchee": "^4.4.6"
"bunchee": "^4.4.6",
"lfs-auto-track": "^1.1.0"
},

@@ -47,0 +48,0 @@ "prettier": {

# Xior
An Axios replacement request library use fetch, and more.
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 ~5KB, Gzip ~2.0KB
- 🤙 Support timeout and cancel request
- 🫡 Similiar `axios.create` / `axios.interceptors.request.use` / `axios.interceptors.response.use` / `.get/post/put/patch/delete/head/options`
- 🔥 Use fetch
- 🚀 Lightweight ~5KB, Gzip ~2.0KB
- 🤙 Support timeout and cancel request
- 👊 Unit tests
- 💪 100% Write in TypeScript
- [ ] 🥷 Plugins support: error retry, cache, repeat requests avoid plugin 😎
- 💪 100% Write in TypeScript
- [ ] **❗️❗️❗️WIP** 🥷 Plugins support: error retry, cache, repeat requests filter plugins 😎

@@ -48,6 +48,182 @@ ## Getting Started

## Usage
### GET / POST
```ts
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]`:
```ts
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 in url encoded strings, use custom encode function `qs`'s `stringify` module:
```ts
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 don't support upload progess or download progress.
Use FormData to upload files.
```ts
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
```ts
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
```ts
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
```
### instance.interceptors.request.use
```ts
import xior, { merge as deepMerge } from 'xior';
const instance = xior.create();
instance.interceptors.request.use((config) => {
return deepMerge(config, {
headers: {
token: localStorage.getItem('token') || '',
},
});
});
```
### instance.interceptors.response.use
```ts
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;
}
);
```
## Use plugins
**❗️❗️❗️ WIP (Work in Progress) ❗️❗️❗️**
```ts
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) ❗️❗️❗️**
```ts
xior.plugins.use(async (request, response, error) => {
import xior from 'xior';
const instance = xior.create();
instance.plugins.use(async (request, response, error) => {
const inRequestPhase = !response;

@@ -68,9 +244,8 @@ const inResponsePhase = Boolean(response);

### FAQ
## FAQ
- Is `xior` 100% compatiable with `axios`? No.
- How to cancel request? Ok
- How to upload files? Ok
- How to show upload progress like axios? Don't support.
- Is `xior` 100% compatiable with `axios`? No
- How to upload files? Use
- How to show upload progress like axios? Not 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!

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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