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.1.4 to 0.2.1

dist/xior.umd.js

47

dist/index.esm.d.ts

@@ -21,2 +21,3 @@ export { merge } from 'ts-deepmerge';

data?: any;
_data?: any;
/** encoded url with params */

@@ -81,2 +82,8 @@ _url?: string;

declare function isAbsoluteURL(url: string): boolean;
/**
* joinPath('/', '/') -> '/'
* joinPath('/a/', '/b') -> '/a/b'
* joinPath('/a', '/b') -> '/a/b'
*/
declare function joinPath(path1: string, path2: string): string;
declare class XiorError extends Error {

@@ -91,9 +98,26 @@ request?: XiorRequestConfig;

type XiorInstance = xior;
declare class xior {
static create(options?: XiorRequestConfig): xior;
static create(options?: XiorRequestConfig): XiorInstance;
static VERSION: string;
config?: XiorRequestConfig;
defaults: XiorInterceptorRequestConfig;
constructor(options?: XiorRequestConfig);
private requestInterceptors;
private responseInterceptors;
requestInterceptors: ((config: XiorInterceptorRequestConfig) => Promise<XiorInterceptorRequestConfig> | XiorInterceptorRequestConfig)[];
responseInterceptors: {
fn: (config: {
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
}) => Promise<{
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
}> | {
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
};
onRejected?: (error: XiorError) => any;
}[];
get interceptors(): {

@@ -147,3 +171,3 @@ request: {

};
private _plugins;
_plugins: XiorPlugin[];
get plugins(): {

@@ -155,5 +179,5 @@ use: (plugin: XiorPlugin) => XiorPlugin;

request<T>(options?: XiorRequestConfig | string): Promise<XiorResponse<T>>;
private handlerFetch;
private createGetHandler;
private createPostHandler;
handlerFetch<T>(requestConfig: XiorRequestConfig): Promise<XiorResponse<T>>;
createGetHandler<T>(method: string): (url: string, options?: XiorRequestConfig) => Promise<XiorResponse<T>>;
createPostHandler<T>(method: string): (url: string, data?: any, options?: XiorRequestConfig) => Promise<XiorResponse<T>>;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;

@@ -165,5 +189,10 @@ head<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;

delete<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
}
export { type ClearableSignal, type ICacheLike, XiorError, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, buildSortedURL, xior as default, delay, encodeParams, isAbsoluteURL, xior };
declare const xiorObj: xior & {
create: typeof xior.create;
VERSION: string;
};
export { type ClearableSignal, type ICacheLike, XiorError, type XiorInstance, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, buildSortedURL, xiorObj as default, delay, encodeParams, isAbsoluteURL, joinPath, xior };

2

dist/index.esm.js

@@ -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 s(e){r.abort(e),o()}let n=[];for(let t of e){if((null==t?void 0:t.aborted)===!0){s(t.reason);break}if((null==t?void 0:t.addEventListener)!=null){let e=()=>{s(t.reason)};n.push(()=>{(null==t?void 0:t.removeEventListener)!=null&&t.removeEventListener("abort",e)}),t.addEventListener("abort",e)}}function o(){n.forEach(e=>{e()}),null==t||t()}let a=r.signal;return a.clear=o,a}function r(e,t,r){let s=t?r(t):"";s&&(s=e.includes("?")?e+"&"+s:e+"?"+s);let[n,o]=s.split("?");if(o){let e=o.split("&");return`${n}?${e.sort().join("&")}`}return s||e}function s(e){return new Promise(t=>{setTimeout(()=>{t("ok")},e)})}function n(e,t=!0,r=null){if(null==e)return"";let s=[],o=t?encodeURIComponent:e=>e;for(let a in e)if(Object.prototype.hasOwnProperty.call(e,a)){let i=e[a],u=r?`${r}[${o(a)}]`:o(a);if("object"==typeof i){let e=n(i,t,u);""!==e&&s.push(e)}else Array.isArray(i)?i.forEach((e,t)=>{let r=`${u}[${t}]`;s.push(`${o(r)}=${o(e)}`)}):s.push(`${o(u)}=${o(i)}`)}return s.join("&")}function o(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}class a extends Error{constructor(e,t,r){super(e),this.request=t,this.config=t,this.response=r}}class i extends a{}function u(e,t,r,s,n,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(s,n)}function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e}).apply(this,arguments)}let c="application/x-www-form-urlencoded",p="application/json";function d(e){return h.apply(this,arguments)}function h(){var t;return t=function*(t){let r=t.encode||t.paramsSerializer||n,s=!1!==t.encodeURI,o=t.method?t.method.toUpperCase():"GET",a=t.url||"",i=a,u=t.data,d=!1,h=(null==t?void 0:t.headers)||{};if(u&&!(u instanceof FormData)){let n="";if(null==t?void 0:t.headers){let e=Object.keys(t.headers).find(e=>"content-type"===e.toLowerCase());e&&(n=t.headers[e])}if(n||(n="GET"===o||"HEAD"===o?c:p,h["Content-Type"]=n),n===c&&("object"==typeof u||t.params)){d=!0;let n=r(e(u||{},t.params||{}),s);n&&(a=a.includes("?")?a+=`&${n}`:`${a}?${n}`),u=null}else n===p&&(u=JSON.stringify(u))}return!d&&t.params&&Object.keys(t.params).length>0&&(a=a.includes("?")?a+=`&${r(t.params,s)}`:`${a}?${r(t.params,s)}`),l({},t,{data:u,url:i,_url:a,method:o,headers:h,encode:r,paramsSerializer:r})},(h=function(){var e=this,r=arguments;return new Promise(function(s,n){var o=t.apply(e,r);function a(e){u(o,s,n,a,i,"next",e)}function i(e){u(o,s,n,a,i,"throw",e)}a(void 0)})}).apply(this,arguments)}function f(e,t,r,s,n,o,a){try{var i=e[o](a),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(s,n)}function y(e){return function(){var t=this,r=arguments;return new Promise(function(s,n){var o=e.apply(t,r);function a(e){f(o,s,n,a,i,"next",e)}function i(e){f(o,s,n,a,i,"throw",e)}a(void 0)})}}function m(){return(m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e}).apply(this,arguments)}let v="undefined"!=typeof AbortController;class g{static create(e){return new g(e)}get interceptors(){return{request:{use:(e,t)=>(this.requestInterceptors.push(e),e),eject:e=>{this.requestInterceptors=this.requestInterceptors.filter(t=>t!==e)},clear:()=>{this.requestInterceptors=[this.requestInterceptors[0]]}},response:{use:(e,t)=>(this.responseInterceptors.push({fn:e,onRejected:t}),e),eject:e=>{this.responseInterceptors=this.responseInterceptors.filter(t=>t.fn!==e)},clear:()=>{this.responseInterceptors=[]}}}}get plugins(){return{use:e=>(this._plugins.push(e),e),eject:e=>{this._plugins=this._plugins.filter(t=>t!==e)},clear:()=>{this._plugins=[]}}}request(t){var r=this;return y(function*(){let s=e({},r.config||{},r.defaults||{},"string"==typeof t?{url:t}:t||{},{headers:{},params:{}});for(let e of r.requestInterceptors)s=yield e(s);let n=r.handlerFetch.bind(r);return r._plugins.forEach(e=>{n=e(n)}),n(s)})()}handlerFetch(e){var r=this;return y(function*(){var s;let n,u;let{url:l,method:c,headers:p,timeout:d,signal:h,data:f}=e,y=function(e,t){if(null==e)return{};var r,s,n={},o=Object.keys(e);for(s=0;s<o.length;s++)t.indexOf(r=o[s])>=0||(n[r]=e[r]);return n}(e,["url","method","headers","timeout","signal","data"]),g=[];if(d&&v){let t=new AbortController;u=setTimeout(()=>{t.abort(new i(`timeout of ${d}ms exceeded`,e))},d),g.push(t.signal)}h&&g.push(h),n=g[0],g.length>1&&(n=t(g,()=>{clearTimeout(u)}));let T=e._url||l||"";e.baseURL&&!o(T)&&(T=(e.baseURL.endsWith("/")?e.baseURL:e.baseURL+"/")+(T.startsWith("/")?T.slice(1):T));let b=yield fetch(T,m({body:["HEAD","GET"].includes(e.method||"GET")?void 0:f},y,{signal:n,method:c,headers:p}));if(u&&clearTimeout(u),null==n||null==(s=n.clear)||s.call(n),!b.ok){let t;try{(t=yield b.text())&&(t=JSON.parse(t))}catch(e){}let s=new a(b.status?`Request failed with status code ${b.status}`:"Network error",e,{response:b,data:t,config:e,status:b.status,statusText:b.statusText,headers:b.headers});for(let e of r.responseInterceptors)e.onRejected&&(yield e.onRejected(s));throw s}if("HEAD"===e.method)return{data:void 0,request:e,config:e,response:b,headers:b.headers,status:b.status,statusText:b.statusText};if(!e.responseType||"json"===e.responseType||"text"===e.responseType){let t;try{t={data:yield b.text()};try{t.data&&"text"!==e.responseType&&(t.data=JSON.parse(t.data))}catch(e){}}catch(e){t={data:void 0}}let s={data:t.data,request:e,response:b};for(let e of r.responseInterceptors)s=yield e.fn(s);return{data:s.data,request:e,config:e,response:b,headers:b.headers,status:b.status,statusText:b.statusText}}return{data:void 0,request:e,config:e,response:b,headers:b.headers,status:b.status,statusText:b.statusText}})()}createGetHandler(e){return(t,r)=>this.request(r?m({},r,{method:e,url:t}):{method:e,url:t})}createPostHandler(e){return(t,r,s)=>this.request(s?m({},s,{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){return this.createGetHandler("DELETE")(e,t)}options(e,t,r){return this.createPostHandler("OPTIONS")(e,t,r)}constructor(e){this.requestInterceptors=[d],this.responseInterceptors=[],this._plugins=[],this.config=e,this.defaults={params:{},headers:{}}}}export{a as XiorError,i as XiorTimeoutError,t as anySignal,r as buildSortedURL,g as default,s as delay,n as encodeParams,o as isAbsoluteURL,g 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 i=r.signal;return i.clear=o,i}function r(e,t,r){let n=t?r(t):"";n&&(n=e.includes("?")?e+"&"+n:e+"?"+n);let[s,o]=n.split("?");if(o){let e=o.split("&");return`${s}?${e.sort().join("&")}`}return n||e}function n(e){return new Promise(t=>{setTimeout(()=>{t("ok")},e)})}function s(e,t=!0,r=null){if(null==e)return"";let n=[],o=t?encodeURIComponent:e=>e;for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let a=e[i],l=r?`${r}[${o(i)}]`:o(i);if("object"==typeof a){let e=s(a,t,l);""!==e&&n.push(e)}else Array.isArray(a)?a.forEach((e,t)=>{let r=`${l}[${t}]`;n.push(`${o(r)}=${o(e)}`)}):n.push(`${o(l)}=${o(a)}`)}return n.join("&")}function o(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function i(e,t){return t?(e.endsWith("/")?e:e+"/")+(t.startsWith("/")?t.slice(1):t):e}class a extends Error{constructor(e,t,r){super(e),this.request=t,this.config=t,this.response=r}}class l extends a{}function u(e,t,r,n,s,o,i){try{var a=e[o](i),l=a.value}catch(e){r(e);return}a.done?t(l):Promise.resolve(l).then(n,s)}function c(){return(c=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 p="application/x-www-form-urlencoded",d="application/json";function h(e="GET"){return["HEAD","GET","DELETE","OPTIONS"].includes(e)}function f(e){return m.apply(this,arguments)}function m(){var t;return t=function*(t){let r=t.encode||t.paramsSerializer||s,n=!1!==t.encodeURI,o=t.method?t.method.toUpperCase():"GET",i=t.url||"",a=i,l=t.data,u=l,f=!1,m=(null==t?void 0:t.headers)||{};if(l&&!(l instanceof FormData)){let s="";if(null==t?void 0:t.headers){let e=Object.keys(t.headers).find(e=>"content-type"===e.toLowerCase());e&&(s=t.headers[e])}if(s||(s=h(o)?p:d,m["Content-Type"]=s),s===p&&("object"==typeof l||t.params)){f=!0;let s=r(e(l||{},t.params||{}),n);s&&(i=i.includes("?")?i+=`&${s}`:`${i}?${s}`)}else s===d&&(u=JSON.stringify(l))}return!f&&t.params&&Object.keys(t.params).length>0&&(i=i.includes("?")?i+=`&${r(t.params,n)}`:`${i}?${r(t.params,n)}`),c({},t,{data:l,_data:u,url:a,_url:i,method:o,headers:m,encode:r,paramsSerializer:r})},(m=function(){var e=this,r=arguments;return new Promise(function(n,s){var o=t.apply(e,r);function i(e){u(o,n,s,i,a,"next",e)}function a(e){u(o,n,s,i,a,"throw",e)}i(void 0)})}).apply(this,arguments)}function v(e,t,r,n,s,o,i){try{var a=e[o](i),l=a.value}catch(e){r(e);return}a.done?t(l):Promise.resolve(l).then(n,s)}function y(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function i(e){v(o,n,s,i,a,"next",e)}function a(e){v(o,n,s,i,a,"throw",e)}i(void 0)})}}function g(){return(g=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 b="undefined"!=typeof AbortController;class E{static create(e){return new E(e)}get interceptors(){return{request:{use:(e,t)=>(this.requestInterceptors.push(e),e),eject:e=>{this.requestInterceptors=this.requestInterceptors.filter(t=>t!==e)},clear:()=>{this.requestInterceptors=[this.requestInterceptors[0]]}},response:{use:(e,t)=>(this.responseInterceptors.push({fn:e,onRejected:t}),e),eject:e=>{this.responseInterceptors=this.responseInterceptors.filter(t=>t.fn!==e)},clear:()=>{this.responseInterceptors=[]}}}}get plugins(){return{use:e=>(this._plugins.push(e),e),eject:e=>{this._plugins=this._plugins.filter(t=>t!==e)},clear:()=>{this._plugins=[]}}}request(t){var r=this;return y(function*(){let n=e({},r.config||{},r.defaults||{},"string"==typeof t?{url:t}:t||{},{headers:{},params:{}});for(let e of r.requestInterceptors)n=yield e(n);let s=r.handlerFetch.bind(r);return r._plugins.forEach(e=>{s=e(s)}),s(n)})()}handlerFetch(e){var r=this;return y(function*(){var n,s;let u,c;let{url:p,method:d,headers:f,timeout:m,signal:v,data:y,_data:E}=e,O=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}(e,["url","method","headers","timeout","signal","data","_data"]),j=[];if(m&&b){let t=new AbortController;c=setTimeout(()=>{t.abort(new l(`timeout of ${m}ms exceeded`,e))},m),j.push(t.signal)}v&&j.push(v),u=j[0],j.length>1&&(u=t(j,()=>{clearTimeout(c)}));let I=e._url||p||"";e.baseURL&&!o(I)&&(I=i(e.baseURL,I));let w=yield fetch(I,g({body:h(e.method)?void 0:E},O,{signal:u,method:d,headers:f}));c&&clearTimeout(c),null==u||null==(n=u.clear)||n.call(u);let T={response:w,config:e,status:w.status,statusText:w.statusText,headers:w.headers};if(!w.ok){let t;try{(t=yield w.text())&&(t=JSON.parse(t))}catch(e){}let n=new a(w.status?`Request failed with status code ${w.status}`:"Network error",e,g({data:t},T));for(let e of r.responseInterceptors)if(e.onRejected){let t=yield e.onRejected(n);if(null==t?void 0:null==(s=t.response)?void 0:s.ok)return t}throw n}if("HEAD"===e.method)return g({data:void 0,request:e},T);let{responseType:P}=e;if(!P||"json"===P||"text"===P){let t;try{(t=yield w.text())&&"text"!==P&&(t=JSON.parse(t))}catch(e){}let n={data:t,request:e,response:w};for(let e of r.responseInterceptors)n=yield e.fn(n);return g({data:n.data,request:e},T)}return g({data:void 0,request:e},T)})()}createGetHandler(e){return(t,r)=>this.request(r?g({},r,{method:e,url:t}):{method:e,url:t})}createPostHandler(e){return(t,r,n)=>this.request(n?g({},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){return this.createGetHandler("DELETE")(e,t)}options(e,t){return this.createGetHandler("OPTIONS")(e,t)}constructor(e){this.requestInterceptors=[f],this.responseInterceptors=[],this._plugins=[],this.config=e,this.defaults={params:{},headers:{}}}}E.VERSION="0.2.1";let O=Object.assign(E.create(),{create:E.create,VERSION:E.VERSION});export{a as XiorError,l as XiorTimeoutError,t as anySignal,r as buildSortedURL,O as default,n as delay,s as encodeParams,o as isAbsoluteURL,i as joinPath,E as xior};

@@ -21,2 +21,3 @@ export { merge } from 'ts-deepmerge';

data?: any;
_data?: any;
/** encoded url with params */

@@ -81,2 +82,8 @@ _url?: string;

declare function isAbsoluteURL(url: string): boolean;
/**
* joinPath('/', '/') -> '/'
* joinPath('/a/', '/b') -> '/a/b'
* joinPath('/a', '/b') -> '/a/b'
*/
declare function joinPath(path1: string, path2: string): string;
declare class XiorError extends Error {

@@ -91,9 +98,26 @@ request?: XiorRequestConfig;

type XiorInstance = xior;
declare class xior {
static create(options?: XiorRequestConfig): xior;
static create(options?: XiorRequestConfig): XiorInstance;
static VERSION: string;
config?: XiorRequestConfig;
defaults: XiorInterceptorRequestConfig;
constructor(options?: XiorRequestConfig);
private requestInterceptors;
private responseInterceptors;
requestInterceptors: ((config: XiorInterceptorRequestConfig) => Promise<XiorInterceptorRequestConfig> | XiorInterceptorRequestConfig)[];
responseInterceptors: {
fn: (config: {
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
}) => Promise<{
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
}> | {
data: any;
request: XiorInterceptorRequestConfig;
response: Response;
};
onRejected?: (error: XiorError) => any;
}[];
get interceptors(): {

@@ -147,3 +171,3 @@ request: {

};
private _plugins;
_plugins: XiorPlugin[];
get plugins(): {

@@ -155,5 +179,5 @@ use: (plugin: XiorPlugin) => XiorPlugin;

request<T>(options?: XiorRequestConfig | string): Promise<XiorResponse<T>>;
private handlerFetch;
private createGetHandler;
private createPostHandler;
handlerFetch<T>(requestConfig: XiorRequestConfig): Promise<XiorResponse<T>>;
createGetHandler<T>(method: string): (url: string, options?: XiorRequestConfig) => Promise<XiorResponse<T>>;
createPostHandler<T>(method: string): (url: string, data?: any, options?: XiorRequestConfig) => Promise<XiorResponse<T>>;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;

@@ -165,5 +189,10 @@ head<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;

delete<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
}
export { type ClearableSignal, type ICacheLike, XiorError, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, buildSortedURL, xior as default, delay, encodeParams, isAbsoluteURL, xior };
declare const xiorObj: xior & {
create: typeof xior.create;
VERSION: string;
};
export { type ClearableSignal, type ICacheLike, XiorError, type XiorInstance, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, buildSortedURL, xiorObj as default, delay, encodeParams, isAbsoluteURL, joinPath, xior };
{
"name": "xior",
"version": "0.1.4",
"description": "A lite request lib based on **fetch** with plugins support, and axios similar API",
"version": "0.2.1",
"description": "A lite request lib based on fetch with plugins support, and axios similar API",
"repository": "suhaotian/xior",

@@ -24,2 +24,8 @@ "bugs": "https://github.com/suhaotian/xior/issues",

},
"./plugins/dedupe": {
"types": "./plugins/dedupe/index.d.ts",
"require": "./plugins/dedupe/index.cjs",
"import": "./plugins/dedupe/index.mjs",
"module": "./plugins/dedupe/index.esm.js"
},
"./plugins/cache": {

@@ -37,2 +43,14 @@ "types": "./plugins/cache/index.d.ts",

},
"./plugins/mock": {
"types": "./plugins/mock/index.d.ts",
"require": "./plugins/mock/index.cjs",
"import": "./plugins/mock/index.mjs",
"module": "./plugins/mock/index.esm.js"
},
"./plugins/error-cache": {
"types": "./plugins/error-cache/index.d.ts",
"require": "./plugins/error-cache/index.cjs",
"import": "./plugins/error-cache/index.mjs",
"module": "./plugins/error-cache/index.esm.js"
},
".": {

@@ -45,12 +63,2 @@ "types": "./dist/types/index.d.ts",

},
"scripts": {
"build": "bunchee -m",
"build:lib": "rm -rf lib && tsc --project tsconfig.json",
"test": "pnpm build:lib && node --test",
"checktype": "tsc --noEmit",
"start-publish": "pnpm build && pnpm test && npm publish --registry=https://registry.npmjs.org",
"push": "git push && git lfs push --all origin",
"prepare": "is-ci || pnpm build && husky",
"checksize": "pnpm --filter=vite-example build"
},
"dependencies": {

@@ -60,52 +68,6 @@ "ts-deepmerge": "^7.0.0",

},
"devDependencies": {
"husky": "^9.0.7",
"lint-staged": "^15.2.0",
"prettier": "^3.2.4",
"is-ci": "^3.0.1",
"typescript": "^5.3.3",
"@types/node": "^20.11.13",
"eslint-config-universe": "^12.0.0",
"@tsconfig/recommended": "^1.0.3",
"@types/mime": "^3.0.4",
"express": "^4.18.2",
"@types/express": "^4.17.21",
"axios": "^1.6.7",
"multer": "^1.4.5-lts.1",
"@types/multer": "^1.4.11",
"qs": "^6.11.2",
"@types/qs": "^6.9.11",
"bunchee": "^4.4.8",
"lfs-auto-track": "^1.1.0",
"isomorphic-unfetch": "^4.0.2",
"promise-polyfill": "^8.3.0"
},
"prettier": {
"printWidth": 100,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "es5",
"bracketSameLine": true
},
"eslintConfig": {
"extends": "eslint-config-universe",
"ignorePatterns": [
"node_modules"
]
},
"lint-staged": {
"*": [
"lfs-auto-track 'image,video,audio:100kb;*:1024kb'"
],
"*.{ts,tsx,mts}": [
"prettier --write",
"eslint --fix"
],
"*.{md,css,js,mjs}": [
"prettier --write"
]
},
"files": [
"dist",
"plugins"
"plugins",
"Mock-plugin.md"
],

@@ -126,2 +88,4 @@ "keywords": [

"uri",
"mock",
"dedupe",
"promise",

@@ -135,2 +99,2 @@ "request",

"license": "MIT"
}
}

@@ -28,2 +28,3 @@ type ICacheLike<T> = {

data?: any;
_data?: any;
/** encoded url with params */

@@ -60,3 +61,3 @@ _url?: string;

/**
* check if we need enable cache, default only `GET` method enable cache
* check if we need enable cache, default only `GET` method or`isGet: true` enable cache
*/

@@ -63,0 +64,0 @@ enableCache?: boolean | ((config?: XiorRequestConfig) => boolean);

@@ -28,2 +28,3 @@ type ICacheLike<T> = {

data?: any;
_data?: any;
/** encoded url with params */

@@ -60,3 +61,3 @@ _url?: string;

/**
* check if we need enable cache, default only `GET` method enable cache
* check if we need enable cache, default only `GET` method or`isGet: true` enable cache
*/

@@ -63,0 +64,0 @@ enableCache?: boolean | ((config?: XiorRequestConfig) => boolean);

@@ -19,2 +19,3 @@ interface XiorRequestConfig<T = any> extends Omit<RequestInit, 'body'> {

data?: any;
_data?: any;
/** encoded url with params */

@@ -21,0 +22,0 @@ _url?: string;

@@ -19,2 +19,3 @@ interface XiorRequestConfig<T = any> extends Omit<RequestInit, 'body'> {

data?: any;
_data?: any;
/** encoded url with params */

@@ -21,0 +22,0 @@ _url?: string;

@@ -19,2 +19,3 @@ interface XiorRequestConfig<T = any> extends Omit<RequestInit, 'body'> {

data?: any;
_data?: any;
/** encoded url with params */

@@ -21,0 +22,0 @@ _url?: string;

@@ -19,2 +19,3 @@ interface XiorRequestConfig<T = any> extends Omit<RequestInit, 'body'> {

data?: any;
_data?: any;
/** encoded url with params */

@@ -21,0 +22,0 @@ _url?: string;

@@ -28,2 +28,3 @@ type ICacheLike<T> = {

data?: any;
_data?: any;
/** encoded url with params */

@@ -66,3 +67,3 @@ _url?: string;

/**
* check if we need enable throttle, default only `GET` method enable
* check if we need enable throttle, default only `GET` method or`isGet: true` enable
*/

@@ -69,0 +70,0 @@ enableThrottle?: boolean | ((config?: XiorRequestConfig) => boolean);

@@ -28,2 +28,3 @@ type ICacheLike<T> = {

data?: any;
_data?: any;
/** encoded url with params */

@@ -66,3 +67,3 @@ _url?: string;

/**
* check if we need enable throttle, default only `GET` method enable
* check if we need enable throttle, default only `GET` method or`isGet: true` enable
*/

@@ -69,0 +70,0 @@ enableThrottle?: boolean | ((config?: XiorRequestConfig) => boolean);

@@ -17,3 +17,3 @@ [![Build](https://github.com/suhaotian/xior/actions/workflows/check.yml/badge.svg)](https://github.com/suhaotian/xior/actions/workflows/check.yml)

- 🤙 Support timeout and cancel requests
- 🥷 Plugin support: error retry, cache, throttling, and easily create custom plugins
- 🥷 Plugin support: error retry, cache, throttling, dedupe, error cache, mock and easily create custom plugins
- 🚀 Lightweight (~6KB, Gzip ~2.6KB)

@@ -31,4 +31,8 @@ - 👊 Unit tested and strongly typed 💪

- [Installing](#installing)
- [Package manager](#package-manager)
- [Use CDN](#use-cdn)
- [Create instance](#create-instance)
- [GET / POST / DELETE / PUT / PATCH / OPTIONS / HEAD](#get--post--delete--put--patch--options--head)
- [Change default headers or params](#change-default-headers-or-params)
- [Get response headers](#get-response-headers)
- [Upload file](#upload-file)

@@ -40,4 +44,7 @@ - [Using interceptors](#using-interceptors)

- [Request throttle plugin](#request-throttle-plugin)
- [Request dedupe plugin](#request-dedupe-plugin)
- [Error cache plugin](#error-cache-plugin)
- [Cache plugin](#cache-plugin)
- [Upload and download progress plugin](#upload-and-download-progress-plugin)
- [Mock plugin](#mock-plugin)
- [Create your own custom plugin](#create-your-own-custom-plugin)

@@ -55,3 +62,5 @@ - [Helper functions](#helper-functions)

- [POST](#post)
- [`axios(requestObj)`: axios({ method: 'get', params: { a: 1 } })](#axiosrequestobj-axios-method-get-params--a-1--)
- [Creating an instance](#creating-an-instance)
- [Get response headers](#get-response-headers-1)
- [Download file with `responseType: 'stream'` (In Node.JS)](#download-file-with-responsetype-stream-in-nodejs)

@@ -91,2 +100,4 @@ - [Use stream](#use-stream)

#### Package manager
```sh

@@ -106,2 +117,36 @@ # npm

#### Use CDN
> Since v0.2.1, xior support UMD format now :()
Use jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.get('https://exmapledomain.com/api').then((res) => {
console.log(res.data);
});
</script>
```
Use unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Usage -->
<script>
xior.plugins.use(xiorProgress());
xior.get('https://exmapledomain.com/api').then((res) => {
console.log(res.data);
});
</script>
```
### Create instance

@@ -124,3 +169,3 @@

> `HEAD` method is same usage with `GET`
> `HEAD` / `DELETE` / `OPTIONS` are same usage with `GET` method

@@ -149,3 +194,3 @@ ```ts

> `DELETE`/`PUT`/`PATCH`/`OPTIONS` methods are same usage with `POST`
> `PUT`/`PATCH` methods are same usage with `POST`

@@ -167,2 +212,36 @@ ```ts

### Change default headers or params
```ts
import xior from 'xior';
export const xiorInstance = xior.create({
baseURL: 'https://apiexampledomian.com/api',
});
function setAccessToken(token: string) {
// xiorInstance.defaults.params['x'] = 1;
xiorInstance.defaults.headers['Authorization'] = `Bearer ${token}`;
}
function removeUserToken() {
// delete xiorInstance.defaults.params['x'];
delete xiorInstance.defaults.headers['Authorization'];
}
```
### Get response headers
```ts
import xior from 'xior';
const xiorInstance = xior.create({
baseURL: 'https://apiexampledomian.com/api',
});
const { data, headers } = await xiorInstance.get('/');
console.log(headers.get('X-Header-Name'));
```
### Upload file

@@ -291,5 +370,8 @@

- [Error retry plugin](#error-retry-plugin)
- [Request dedupe plugin](#request-dedupe-plugin)
- [Request throttle plugin](#request-throttle-plugin)
- [Error cache plugin](#error-cache-plugin)
- [Cache plugin](#cache-plugin)
- [Upload and download progress plugin](#upload-and-download-progress-plugin)
- [Mock plugin](#Mock-plugin)

@@ -323,3 +405,3 @@ Usage:

retryInterval?: number;
enableRetry?: boolean | (error: Xiorconfig, error: XiorRequestConfig) => boolean;
enableRetry?: boolean | (config: XiorRequestConfig, error: XiorError) => boolean;
}): XiorPlugin;

@@ -330,7 +412,7 @@ ```

| Param | Type | Default value | Description |
| ------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| retryTimes | number | 2 | Set the retry times for failed request |
| retryInterval | number | 3000 | After first time retry, the next retries interval time, default interval is 3 seconds |
| enableRetry | boolean \| ((config: Xiorconfig, error: XiorRequestConfig) => boolean) | (config, error) => config.method === 'GET' \|\| config.isGet | Default only retry if `GET` request error and `retryTimes > 0` |
| Param | Type | Default value | Description |
| ------------- | --------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| retryTimes | number | 2 | Set the retry times for failed request |
| retryInterval | number | 3000 | After first time retry, the next retries interval time, default interval is 3 seconds |
| enableRetry | boolean \| ((config: XiorRequestConfig, error: XiorError) => boolean) | (config, error) => config.method === 'GET' \|\| config.isGet | Default only retry if `GET` request error and `retryTimes > 0` |

@@ -364,2 +446,35 @@ Basic usage:

Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/error-retry.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorErrorRetry());
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/error-retry.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorErrorRetry());
</script>
```
### Request throttle plugin

@@ -376,3 +491,3 @@

/**
* check if we need enable throttle, default only `GET` method enable
* check if we need enable throttle, default only `GET` method or`isGet: true` enable
*/

@@ -434,2 +549,177 @@ enableThrottle?: boolean | ((config?: XiorRequestConfig) => boolean);

Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/throttle.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorThrottle());
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/throttle.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorThrottle());
</script>
```
### Request dedupe plugin
> Prevents having multiple identical requests on the fly at the same time.
API:
```ts
function dedupeRequestPlugin(options: {
/**
* check if we need enable dedupe, default only `GET` method or`isGet: true` enable
*/
enableDedupe?: boolean | ((config?: XiorRequestConfig) => boolean);
}): XiorPlugin;
```
Basic usage:
```ts
import xior from 'xior';
import dedupePlugin from 'xior/plugins/dedupe';
const http = xior.create();
http.plugins.use(dedupePlugin());
http.get('/'); // make real http request
http.get('/'); // response from previous if previous request return response
http.get('/'); // response from previous if previous request return response
http.post('/'); // make real http request
http.post('/'); // make real http request
http.post('/'); // make real http request
```
Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/dedupe.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorDedupe());
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/dedupe.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorDedupe());
</script>
```
### Error cache plugin
> When request error, if have cached data then use the cached data
API:
```ts
function errorCachePlugin(options: {
enableCache?: boolean | ((config?: XiorRequestConfig) => boolean);
defaultCache?: ICacheLike<XiorPromise>;
}): XiorPlugin;
```
The `options` object:
| Param | Type | Default value | Description |
| ------------ | -------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| enableCache | boolean \| ((config: Xiorconfig) => boolean) | (config) => config.method === 'GET' \|\| config.isGet | Default only enabled in `GET` request |
| defaultCache | CacheLike | lru(Inifinite, 0) | will used for storing requests by default, except you define a custom Cache with your request config, use `tiny-lru` module |
Basic usage:
```ts
import xior from 'xior';
import errorCachePlugin from 'xior/plugins/error-cache';
const http = xior.create();
http.plugins.use(errorCachePlugin({}));
http.get('/users'); // make real http request, and cache the response
const res = await http.get('/users'); // if request error, use the cache data
if (res.fromCache) {
// if `fromCache` is true, means data from cache!
console.log('data from cache!');
// and get what's the error
console.log('error', res.error);
}
http.post('/users'); // no cache for post
http.post('/users', { isGet: true }); // but with `isGet: true` can let plugins know this is `GET` behavior! then will cache data
```
Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/error-cache.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorErrorCache());
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/error-cache.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorErrorCache());
</script>
```
### Cache plugin

@@ -441,2 +731,4 @@

> Different with `error-cache` plugin: this plugin will use the data in cache if the cache data not expired.
API:

@@ -469,3 +761,3 @@

http.get('/users'); // get cache from previous request
http.get('/users', { enableCache: false }); // disable cache manually and the the real http request
http.get('/users', { enableCache: false }); // disable cache manually and the real http request

@@ -478,3 +770,3 @@ http.post('/users'); // default no cache for post

if (res.fromCache) {
// if fromCache is true, means data from cache!
// if `fromCache` is true, means data from cache!
console.log('data from cache!');

@@ -556,2 +848,160 @@ }

Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/progress.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorProgress());
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/progress.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
xior.plugins.use(xiorProgress());
</script>
```
### Mock plugin
> This plugin let you eaisly mock requests
Usage:
with `GET`:
```ts
import xior from 'xior';
import MockPlugin from 'xior/plugins/mock';
const instance = xior.create();
const mock = new MockPlugin(instance);
// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(
200,
{
users: [{ id: 1, name: 'John Smith' }],
},
{
'X-Custom-Response-Header': '123',
}
);
instance.get('/users').then(function (response) {
console.log(response.data);
console.log(response.headers.get('X-Custom-Response-Header')); // 123
});
// Mock GET request to /users when param `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onGet('/users', { params: { searchText: 'John' } }).reply(200, {
users: [{ id: 1, name: 'John Smith' }],
});
instance.get('/users', { params: { searchText: 'John' } }).then(function (response) {
console.log(response.data);
});
```
with `POST`:
```ts
import xior from 'xior';
import MockPlugin from 'xior/plugins/mock';
const instance = xior.create();
const mock = new MockPlugin(instance);
// Mock any POST request to /users
// arguments for reply are (status, data, headers)
mock.onPost('/users').reply(
200,
{
users: [{ id: 1, name: 'John Smith' }],
},
{
'X-Custom-Response-Header': '123',
}
);
instance.post('/users').then(function (response) {
console.log(response.data);
console.log(response.headers.get('X-Custom-Response-Header')); // 123
});
// Mock POST request to /users when param `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onPost('/users', null, { params: { searchText: 'John' } }).reply(200, {
users: [{ id: 1, name: 'John Smith' }],
});
instance.get('/users', null, { params: { searchText: 'John' } }).then(function (response) {
console.log(response.data);
});
// Mock POST request to /users when body `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onPost('/users', { searchText: 'John' }).reply(200, {
users: [{ id: 1, name: 'John Smith' }],
});
instance.get('/users', { searchText: 'John' }).then(function (response) {
console.log(response.data);
});
```
**More details**, [check here](./Mock-plugin.md).
Use CDN:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://cdn.jsdelivr.net/npm/xior@0.2.1/plugins/mock.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
const mock = new xiorMock(xior);
</script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/xior@0.2.1/dist/xior.umd.js"></script>
<!-- Load plugin -->
<script src="https://unpkg.com/xior@0.2.1/plugins/mock.umd.js"></script>
<!-- Usage -->
<script>
console.log(xior.VERSION);
const mock = new xiorMock(xior);
</script>
```
### Create your own custom plugin

@@ -595,2 +1045,3 @@

isAbsoluteURL,
joinPath,
} from 'xior';

@@ -700,6 +1151,4 @@ ```

```ts
import xior from 'xior';
import axios from 'xior';
const axios = xior.create();
// Make a request for a user with a given ID

@@ -771,6 +1220,4 @@ axios

```ts
import xior from 'xior';
import axios from 'xior';
const axios = xior.create();
axios

@@ -789,2 +1236,22 @@ .post('/user', {

### `axios(requestObj)`: axios({ method: 'get', params: { a: 1 } })
axios:
```ts
import axios from 'axios';
await axios({ method: 'get', params: { a: 1 } });
```
xior:
```ts
import xior from 'xior';
const axios = xior.create();
await axios.request({ method: 'get', params: { a: 1 } });
```
### Creating an instance

@@ -814,2 +1281,32 @@

### Get response headers
axios:
```ts
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'https://apiexampledomian.com/api',
});
const { data, headers } = await axiosInstance.get('/');
console.log(headers['X-Header-Name']);
```
xior:
```ts
import xior from 'xior';
const xiorInstance = xior.create({
baseURL: 'https://apiexampledomian.com/api',
});
const { data, headers } = await xiorInstance.get('/');
console.log(headers.get('X-Header-Name'));
```
### Download file with `responseType: 'stream'` (In Node.JS)

@@ -816,0 +1313,0 @@

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

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

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