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

Comparing version 0.0.5 to 0.0.6

lib/plugins/utils.d.ts

88

dist/index.esm.d.ts

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

}
type XiorPlugin = (adapter: (request: XiorRequestConfig) => Promise<XiorResponse>) => (request: XiorRequestConfig) => Promise<XiorResponse<any>>;

@@ -62,76 +63,17 @@ declare class xior {

};
request<T>(options?: XiorRequestConfig | string): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
private _plugins;
get plugins(): {
use: (plugin: XiorPlugin) => void;
};
request<T>(options?: XiorRequestConfig | string): Promise<XiorResponse<T>>;
private handlerFetch;
private createGetHandler;
private createPostHandler;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
}

@@ -166,2 +108,2 @@

export { type ClearableSignal, XiorError, type XiorInterceptorRequestConfig, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, xior as default, encode, isAbsoluteURL, xior };
export { type ClearableSignal, XiorError, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, xior as default, encode, isAbsoluteURL, xior };

@@ -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){var a,i=this;return(a=function*(){var a;let u;let l=e(i.config||{},"string"==typeof r?{url:r}:r||{},{headers:{},params:{}});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 g=T[0];T.length>1&&(g=t(T,()=>{clearTimeout(u)}));let b=l._url||c||"";l.baseURL&&!n(b)&&(b=(l.baseURL.endsWith("/")?l.baseURL:l.baseURL+"/")+(b.startsWith("/")?b.slice(1):b));let x=yield fetch(b,h({body:["HEAD","GET"].includes(l.method||"GET")?void 0:y},m,{signal:g,method:d,headers:p}));if(u&&clearTimeout(u),null==g||null==(a=g.clear)||a.call(g),!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};
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(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var o=e.apply(t,r);function a(e){p(o,n,s,a,i,"next",e)}function i(e){p(o,n,s,a,i,"throw",e)}a(void 0)})}}function f(){return(f=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 v="undefined"!=typeof AbortController;class y{static create(e){return new y(e)}get interceptors(){return{request:{use:(e,t)=>{this.requestInterceptors.push(e)}},response:{use:(e,t)=>{this.responseInterceptors.push({fn:e,onRejected:t})}}}}get plugins(){return{use:e=>{this._plugins.push(e)}}}request(t){var r=this;return h(function*(){let n=e(r.config||{},"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 h(function*(){var a;let i,u;let{url:l,method:c,headers:d,timeout:p,signal:h,data:y}=e,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}(e,["url","method","headers","timeout","signal","data"]),g=[];if(p&&v){let e=new AbortController;u=setTimeout(()=>{e.abort(new s(`timeout of ${p}ms exceeded`))},p),g.push(e.signal)}h&&g.push(h),i=g[0],g.length>1&&(i=t(g,()=>{clearTimeout(u)}));let T=e._url||l||"";e.baseURL&&!n(T)&&(T=(e.baseURL.endsWith("/")?e.baseURL:e.baseURL+"/")+(T.startsWith("/")?T.slice(1):T));let b=yield fetch(T,f({body:["HEAD","GET"].includes(e.method||"GET")?void 0:y},m,{signal:i,method:c,headers:d}));if(u&&clearTimeout(u),null==i||null==(a=i.clear)||a.call(i),!b.ok){let t;try{(t=yield b.text())&&(t=JSON.parse(t))}catch(e){}let n=new o(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(n));throw n}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 n={data:t.data,request:e,response:b};for(let e of r.responseInterceptors)n=yield e.fn(n);return{data:n.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?f({},r,{method:e,url:t}):{method:e,url:t})}createPostHandler(e){return(t,r,n)=>this.request(n?f({},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._plugins=[],this.config=e}}export{o as XiorError,s as XiorTimeoutError,t as anySignal,y as default,r as encode,n as isAbsoluteURL,y as xior};

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

}
type XiorPlugin = (adapter: (request: XiorRequestConfig) => Promise<XiorResponse>) => (request: XiorRequestConfig) => Promise<XiorResponse<any>>;

@@ -62,76 +63,17 @@ declare class xior {

};
request<T>(options?: XiorRequestConfig | string): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
private _plugins;
get plugins(): {
use: (plugin: XiorPlugin) => void;
};
request<T>(options?: XiorRequestConfig | string): Promise<XiorResponse<T>>;
private handlerFetch;
private createGetHandler;
private createPostHandler;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
}

@@ -166,2 +108,2 @@

export { type ClearableSignal, XiorError, type XiorInterceptorRequestConfig, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, xior as default, encode, isAbsoluteURL, xior };
export { type ClearableSignal, XiorError, type XiorInterceptorRequestConfig, type XiorPlugin, type XiorRequestConfig, type XiorResponse, XiorTimeoutError, anySignal, xior as default, encode, isAbsoluteURL, xior };

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

import { XiorInterceptorRequestConfig } from './types';
import type { XiorInterceptorRequestConfig } from './types';
export declare function defaultRequestInterceptor(req: XiorInterceptorRequestConfig): Promise<XiorInterceptorRequestConfig>;

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

export default function xiorErrorRetryPlugin(options?: object): void;
import { XiorPlugin } from '../types';
import { XiorError } from '../utils';
export type ErrorRetryOptions = {
/** retry times, default: 0 */
retryTimes?: number;
/**
* Retry after milliseconds, default: 3000
* after first time error retry, retry interval
*/
retryInterval?: number;
/**
* default: true,
* it's useful because we don't want retry when the error because of token expired
*/
shouldRetryOnError?: (error: XiorError) => boolean;
};
/** @ts-ignore */
declare module 'xior' {
interface XiorRequestConfig extends Omit<ErrorRetryOptions, 'shouldRetryOnError'> {
}
}
export default function xiorErrorRetryPlugin(options?: ErrorRetryOptions): XiorPlugin;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
// TODO
function xiorErrorRetryPlugin(options) {
//
const utils_1 = require("./utils");
const utils_2 = require("../utils");
function xiorErrorRetryPlugin(options = {}) {
const { retryTimes: _retryTimes, retryInterval: _retryInterval, shouldRetryOnError, } = options || {
retryTimes: 0,
retryInterval: 3000,
};
return function (adapter) {
return (config) => __awaiter(this, void 0, void 0, function* () {
const { retryTimes = _retryTimes, retryInterval = _retryInterval } = config;
let timeUp = false;
let count = 0;
function handleRequest() {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield adapter(config);
}
catch (error) {
if (error instanceof utils_2.XiorError || error instanceof utils_2.XiorTimeoutError) {
const shouldRetry = shouldRetryOnError ? shouldRetryOnError(error) : true;
timeUp = retryTimes === count;
if (timeUp || !shouldRetry) {
throw error;
}
if (retryInterval && retryInterval > 0 && count > 0) {
yield (0, utils_1.delay)(retryInterval);
}
count++;
return handleRequest();
}
throw error;
}
});
}
return handleRequest();
});
};
}
exports.default = xiorErrorRetryPlugin;

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

export default function xiorRepeatRequestsFilterPlugin(options?: object): void;
import { XiorPlugin } from '../types';
export default function xiorRepeatRequestFilterPlugin(options?: {}): XiorPlugin;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
// TODO
function xiorRepeatRequestsFilterPlugin(options) {
//
function xiorRepeatRequestFilterPlugin(options = {}) {
return function (adapter) {
return (config) => __awaiter(this, void 0, void 0, function* () {
return adapter(config);
});
};
}
exports.default = xiorRepeatRequestsFilterPlugin;
exports.default = xiorRepeatRequestFilterPlugin;

@@ -32,1 +32,2 @@ export interface XiorRequestConfig<T = any> extends Omit<RequestInit, 'body'> {

}
export type XiorPlugin = (adapter: (request: XiorRequestConfig) => Promise<XiorResponse>) => (request: XiorRequestConfig) => Promise<XiorResponse<any>>;

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

import { XiorRequestConfig, XiorResponse } from './types';
import type { XiorRequestConfig, XiorResponse } from './types';
export * from './any-signals';

@@ -3,0 +3,0 @@ export * from './merge';

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

import { XiorInterceptorRequestConfig, XiorRequestConfig } from './types';
import type { XiorInterceptorRequestConfig, XiorPlugin, XiorRequestConfig, XiorResponse } from './types';
export declare class xior {

@@ -28,76 +28,17 @@ static create(options?: XiorRequestConfig): xior;

};
request<T>(options?: XiorRequestConfig | string): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
private _plugins;
get plugins(): {
use: (plugin: XiorPlugin) => void;
};
request<T>(options?: XiorRequestConfig | string): Promise<XiorResponse<T>>;
private handlerFetch;
private createGetHandler;
private createPostHandler;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<{
data: T;
request: XiorRequestConfig<any>;
config: XiorRequestConfig<any>;
response: Response;
headers: Headers;
status: number;
statusText: string;
}>;
get<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
head<T = any>(url: string, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
post<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
put<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
patch<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
delete<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
options<T = any>(url: string, data?: any, options?: XiorRequestConfig): Promise<XiorResponse<T>>;
}

@@ -26,2 +26,3 @@ "use strict";

const utils_1 = require("./utils");
const supportAbortController = typeof AbortController !== 'undefined';
class xior {

@@ -36,2 +37,3 @@ static create(options) {

this.responseInterceptors = [];
this._plugins = [];
this.config = options;

@@ -55,14 +57,31 @@ }

}
get plugins() {
return {
use: (plugin) => {
this._plugins.push(plugin);
},
};
}
request(options) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
let requestObj = (0, utils_1.merge)(this.config || {}, typeof options === 'string' ? { url: options } : options || {}, { headers: {}, params: {} });
let requestConfig = (0, utils_1.merge)(this.config || {}, typeof options === 'string' ? { url: options } : options || {}, { headers: {}, params: {} });
for (const item of this.requestInterceptors) {
requestObj = yield item(requestObj);
requestConfig = yield item(requestConfig);
}
const { url: _url, method, headers, timeout, signal: reqSignal, data } = requestObj, rest = __rest(requestObj, ["url", "method", "headers", "timeout", "signal", "data"]);
let finalPlugin = this.handlerFetch.bind(this);
this._plugins.forEach((plugin) => {
finalPlugin = plugin(finalPlugin);
});
return finalPlugin(requestConfig);
});
}
handlerFetch(requestConfig) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const { url, method, headers, timeout, signal: reqSignal, data } = requestConfig, rest = __rest(requestConfig, ["url", "method", "headers", "timeout", "signal", "data"]);
/** timeout */
let signal;
const signals = [];
let timer = undefined;
if (timeout) {
if (timeout && supportAbortController) {
const controller = new AbortController();

@@ -77,3 +96,3 @@ timer = setTimeout(() => {

}
let signal = signals[0];
signal = signals[0];
if (signals.length > 1) {

@@ -84,10 +103,10 @@ signal = (0, utils_1.anySignal)(signals, () => {

}
let finalURL = requestObj._url || _url || '';
if (requestObj.baseURL && !(0, utils_1.isAbsoluteURL)(finalURL)) {
const baseURL = requestObj.baseURL.endsWith('/')
? requestObj.baseURL
: requestObj.baseURL + '/';
let finalURL = requestConfig._url || url || '';
if (requestConfig.baseURL && !(0, utils_1.isAbsoluteURL)(finalURL)) {
const baseURL = requestConfig.baseURL.endsWith('/')
? requestConfig.baseURL
: requestConfig.baseURL + '/';
finalURL = baseURL + (finalURL.startsWith('/') ? finalURL.slice(1) : finalURL);
}
const response = yield fetch(finalURL, Object.assign(Object.assign({ body: ['HEAD', 'GET'].includes(requestObj.method || 'GET') ? undefined : data }, rest), { signal,
const response = yield fetch(finalURL, Object.assign(Object.assign({ body: ['HEAD', 'GET'].includes(requestConfig.method || 'GET') ? undefined : data }, rest), { signal,
method,

@@ -108,6 +127,6 @@ headers }));

catch (e) { }
const error = new utils_1.XiorError(!response.status ? `Network error` : `Request failed with status code ${response.status}`, requestObj, {
const error = new utils_1.XiorError(!response.status ? `Network error` : `Request failed with status code ${response.status}`, requestConfig, {
response,
data,
config: requestObj,
config: requestConfig,
status: response.status,

@@ -124,7 +143,7 @@ statusText: response.statusText,

}
if (requestObj.method === 'HEAD') {
if (requestConfig.method === 'HEAD') {
return {
data: undefined,
request: requestObj,
config: requestObj,
request: requestConfig,
config: requestConfig,
response,

@@ -136,5 +155,5 @@ headers: response.headers,

}
if (!requestObj.responseType ||
requestObj.responseType === 'json' ||
requestObj.responseType === 'text') {
if (!requestConfig.responseType ||
requestConfig.responseType === 'json' ||
requestConfig.responseType === 'text') {
let data;

@@ -146,3 +165,3 @@ try {

try {
if (data.data && requestObj.responseType !== 'text') {
if (data.data && requestConfig.responseType !== 'text') {
data.data = JSON.parse(data.data);

@@ -164,3 +183,3 @@ }

data: data.data,
request: requestObj,
request: requestConfig,
response,

@@ -173,4 +192,4 @@ };

data: responseObj.data,
request: requestObj,
config: requestObj,
request: requestConfig,
config: requestConfig,
response,

@@ -184,4 +203,4 @@ headers: response.headers,

data: undefined,
request: requestObj,
config: requestObj,
request: requestConfig,
config: requestConfig,
response,

@@ -188,0 +207,0 @@ headers: response.headers,

{
"name": "xior",
"version": "0.0.5",
"version": "0.0.6",
"description": "Axios similiar API request library but based on fetch",

@@ -27,3 +27,4 @@ "repository": "suhaotian/xior",

"dependencies": {
"ts-deepmerge": "^7.0.0"
"ts-deepmerge": "^7.0.0",
"tiny-lru": "^11.2.5"
},

@@ -48,3 +49,5 @@ "devDependencies": {

"bunchee": "^4.4.6",
"lfs-auto-track": "^1.1.0"
"lfs-auto-track": "^1.1.0",
"isomorphic-unfetch": "^4.0.2",
"promise-polyfill": "^8.3.0"
},

@@ -51,0 +54,0 @@ "prettier": {

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

- 🫡 Similiar `axios.create` / `axios.interceptors.request.use` / `axios.interceptors.response.use` / `.get/post/put/patch/delete/head/options`
- 🔥 Use fetch
- 🔥 Use fetch [why `fetch` instead of `axios`?](#why-use-xior)
- 🚀 Lightweight ~6KB, Gzip ~2.6KB

@@ -22,6 +22,8 @@ - 🤙 Support timeout and cancel request

- 💪 100% Write in TypeScript
- [ ] **❗️❗️❗️WIP** 🥷 Plugins support: error retry, cache, repeat requests filter plugins 😎
- [ ] **❗️❗️❗️WIP** 🥷 Plugins support: error retry, cache, repeat requests filter and easy custom your own plugins 😎
## Install
## Getting Started
Install
```bash

@@ -31,3 +33,3 @@ npm i xior

## Getting Started
Quick start

@@ -107,3 +109,3 @@ ```ts

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

@@ -116,3 +118,3 @@ ```ts

const instance = xior.create({
encode: (params: Record<string, any>) => stringify(params, {}),
encode: (params: Record<string, any>) => stringify(params),
});

@@ -131,3 +133,3 @@ instance.get('http://httpbin.org', {

### Upload data
### Upload file

@@ -160,3 +162,3 @@ > Not like axios, xior doesn't support upload progess or download progress.

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

@@ -236,3 +238,4 @@

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

@@ -260,3 +263,3 @@ ```

**❗️❗️❗️ WIP (Work in Progress) ❗️❗️❗️**
Let's implement a simple custom logs plugin:

@@ -267,15 +270,9 @@ ```ts

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) {
//
}
instance.plugins.use(function logPlugin(adapter) {
return async (config) => {
const start = Date.now();
const res = await adapter(config);
console.log('%s %s take %sms', config.method, config.url, Date.now() - start);
return res;
};
});

@@ -290,2 +287,15 @@ ```

- What about response of `'stream' | 'document' | 'arraybuffer' | 'blob'` ? Use `responseType: 'stream' | 'document' | 'arraybuffer' | 'blob'`, will return original `{ response }`
- How to support old browser? use polyfill, check `src/tests/polyfill.test.ts`
- More: Anything else? create new issues let me know!
### Why use xior?
Xior based on `fetch`, and here are some reasons **why `fetch` instead of `axios`**:
- Built in to node and the browser
- Edge compatible
- Next.js extends the native fetch to [support caching and revalidating](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating)
Why don't just use `fetch`?
Yeah, you can. But xior's API similiar with axios, it's more make sense than the original `fetch`.

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