### Run React Development Server with npm start
Source: https://github.com/suhaotian/xior/blob/main/my-react-app/README.md
Starts the React application in development mode, making it accessible via a local URL (http://localhost:3000). The page automatically reloads upon code changes, and any lint errors are displayed in the console.
```NPM
npm start
```
--------------------------------
### Build React App for Production with npm run build
Source: https://github.com/suhaotian/xior/blob/main/my-react-app/README.md
Builds the React application for production deployment, optimizing it for the best performance. The output is minified, and filenames include hashes, making the app ready for static hosting.
```NPM
npm run build
```
--------------------------------
### Install Bun Project Dependencies
Source: https://github.com/suhaotian/xior/blob/main/bun-example/README.md
This command uses the Bun package manager to install all required dependencies for the project, ensuring the application has all necessary packages to run.
```bash
bun install
```
--------------------------------
### Perform GET Requests with xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Examples of making GET requests using a xior instance, including handling responses, passing query parameters (including nested ones), setting request headers, and specifying response data types.
```typescript
async function run() {
const { data } = await xiorInstance.get('/');
// with params and support nested params
const { data: data2 } = await xiorInstance.get('/', { params: { a: 1, b: 2, c: { d: 1 } } });
// with headers
const { data: data3 } = await xiorInstance.get('/', {
params: { a: 1, b: 2 },
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
// types
const { data: data4 } = await xiorInstance.get<{ field1: string; field2: number }>('/');
}
```
--------------------------------
### Migrate from Axios to Xior: Basic setup
Source: https://github.com/suhaotian/xior/blob/main/README.md
This snippet provides a basic example of migrating from Axios to Xior, showing how to import xior and its related types (XiorError, isXiorError, XiorRequestConfig, XiorResponse). It also demonstrates how to create an xior instance with common configuration like baseURL and timeout, similar to Axios.
```ts
import axios, {
XiorError as AxiosError,
isXiorError as isAxiosError,
XiorRequestConfig as AxiosRequestConfig,
XiorResponse as AxiosResponse,
} from 'xior';
const instance = axios.create({
baseURL: '...',
timeout: 20e3,
});
```
--------------------------------
### Basic Usage of Xior Mock Plugin with TypeScript
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Demonstrates the fundamental setup and usage of the Xior mock plugin in a TypeScript environment. It shows how to create an Xior instance, initialize the mock plugin, and mock a GET request to '/api/hello' with a 200 OK response.
```ts
import xior from 'xior';
import MockPlugin from 'xior/plugins/mock';
const instance = xior.create();
const mock = new MockPlugin(instance);
mock.onGet('/api/hello').reply(200, [{ msg: 'hello' }]);
instance.get('/api/hello').then((res) => {
console.log(res.data); // [{ msg: 'hello' }]
});
```
--------------------------------
### Install Xior and Mock Plugin via Package Managers
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Instructions for installing the Xior HTTP client and its mock plugin using popular Node.js package managers like npm, pnpm, bun, and yarn.
```sh
# npm
npm install xior
# pnpm
pnpm add xior
# bun
bun add xior
# yarn
yarn add xior
```
--------------------------------
### Run Bun Project Application
Source: https://github.com/suhaotian/xior/blob/main/bun-example/README.md
This command executes the main application file, `index.ts`, using the Bun runtime. It starts the project's primary script.
```bash
bun run index.ts
```
--------------------------------
### Launch React Test Runner with npm test
Source: https://github.com/suhaotian/xior/blob/main/my-react-app/README.md
Launches the interactive test runner for the React application. It operates in watch mode, continuously monitoring for changes and re-running relevant tests to provide immediate feedback on code quality.
```NPM
npm test
```
--------------------------------
### Eject Create React App Configuration with npm run eject
Source: https://github.com/suhaotian/xior/blob/main/my-react-app/README.md
Removes the single build dependency from a Create React App project, copying all configuration files (webpack, Babel, ESLint, etc.) directly into the project. This provides full control over the build setup but is a one-way, irreversible operation.
```NPM
npm run eject
```
--------------------------------
### Install Dependencies for Vue CLI Project
Source: https://github.com/suhaotian/xior/blob/main/vue-cli-app/README.md
Installs all necessary project dependencies using Yarn, preparing the Vue CLI application for development or production.
```Shell
yarn install
```
--------------------------------
### Install xior with Yarn
Source: https://github.com/suhaotian/xior/blob/main/README.md
Instructions to add the xior library to your project using the Yarn package manager.
```bash
yarn add xior
```
--------------------------------
### Configure xior with taro-fetch-polyfill for Taro applications
Source: https://github.com/suhaotian/xior/blob/main/README.md
This example provides an illustration of integrating taro-fetch-polyfill's fetch with xior for use in Taro applications. It demonstrates creating an xior instance with the polyfilled fetch and performing a GET request to a specified base URL.
```ts
import { fetch } from 'taro-fetch-polyfill';
import xior from 'xior';
// fetch('https://api.github.com')
// .then(response => response.json())
// .then(console.log);
export const http = xior.create({
baseURL: 'https://github.com/NervJS/taro',
fetch,
});
async function test() {
const { data } = await http.get('/');
return data;
}
```
--------------------------------
### Install xior HTTP Client with Package Managers
Source: https://github.com/suhaotian/xior/blob/main/README.md
Instructions for installing the xior library using popular JavaScript package managers like npm, pnpm, and bun. This provides the core library for making HTTP requests.
```sh
# npm
npm install xior
# pnpm
pnpm add xior
# bun
bun add xior
```
--------------------------------
### Basic Usage of Xior Mock Plugin via unpkg CDN
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Illustrates how to include and use the Xior and Xior mock plugin libraries directly in a web page using the unpkg CDN. It sets up a basic mock for a GET request and logs the response.
```html
```
--------------------------------
### Perform GET Requests with Axios and Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to make basic GET requests using both Axios and Xior, including passing query parameters directly in the URL or via a 'params' object, and handling responses with async/await.
```ts
import axios from 'axios';
// Make a request for a user with a given ID
axios.get('/user?ID=12345');
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345,
},
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
```
```ts
import axios from 'xior';
// Make a request for a user with a given ID
axios.get('/user?ID=12345');
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345,
},
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
```
--------------------------------
### Create a Custom Logging Plugin for xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides an example of creating a simple custom plugin for `xior` that logs request details and response time. The plugin intercepts the request, records the start time, proceeds with the adapter, and then logs the HTTP method, URL, status, and duration before returning the response.
```ts
import xior from 'xior';
const instance = xior.create();
instance.plugins.use(function logPlugin(adapter, instance) {
return async (config) => {
const start = Date.now();
const res = await adapter(config);
console.log('%s %s %s take %sms', config.method, config.url, res.status, Date.now() - start);
return res;
};
});
```
--------------------------------
### Basic Usage of Xior Mock Plugin via jsDelivr CDN
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Illustrates how to include and use the Xior and Xior mock plugin libraries directly in a web page using the jsDelivr CDN. It sets up a basic mock for a GET request and logs the response.
```html
```
--------------------------------
### Use xior via unpkg CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to include the xior library in an HTML page using the unpkg CDN, showing basic usage for making a GET request.
```html
```
--------------------------------
### Basic Usage: Integrating Error Cache Plugin with Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to import and apply the `errorCachePlugin` to a Xior instance. It shows examples of GET and POST requests, illustrating how cached data is used on subsequent erroring requests and how to identify if a response came from the cache.
```TypeScript
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!');
console.log('data cache timestamp: ', res.cacheTime);
// 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
```
--------------------------------
### Mocking GET Requests with Xior Mock Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to use the `MockPlugin` to intercept and mock `GET` requests. It shows mocking a general `GET /users` request with a custom response and headers, and also a conditional mock based on URL parameters.
```typescript
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);
});
```
--------------------------------
### Run Vue CLI Application in Development Mode
Source: https://github.com/suhaotian/xior/blob/main/vue-cli-app/README.md
Starts the development server for the Vue CLI application, enabling hot-reloading for efficient development and testing.
```Shell
yarn serve
```
--------------------------------
### Mocking a GET Request with Xior Mock Plugin
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Demonstrates how to mock a GET request to a specific URL ('/users') using the Xior mock plugin. It shows how to define a custom response including status code, data, and headers, and how to verify the mocked response.
```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
});
```
--------------------------------
### Migrate GET Requests from Fetch to Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Compares how to perform a GET request using the native Fetch API versus the xior library. It highlights xior's `baseURL` and `params` options, which simplify URL construction and parameter handling for cleaner, more maintainable code.
```TypeScript
async function logMovies() {
const response = await fetch('http://example.com/movies.json?page=1&perPage=10');
const movies = await response.json();
console.log(movies);
}
```
```TypeScript
import xior from 'xior';
const http = xior.create({
baseURL: 'http://example.com',
});
async function logMovies() {
const { data: movies } = await http.get('/movies.json', {
params: {
page: 1,
perPage: 10,
},
});
console.log(movies);
}
```
--------------------------------
### Use xior via jsDelivr CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to include the xior library in an HTML page using the jsDelivr CDN, showing basic usage for checking the version and making a GET request.
```html
```
--------------------------------
### Load Xior Dedupe Plugin via CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides examples for loading the Xior library and its dedupe plugin using popular Content Delivery Networks (CDNs) like jsDelivr and unpkg. It shows the necessary `
```
```HTML
```
--------------------------------
### Configuring Xior with Stability and Performance Plugins
Source: https://github.com/suhaotian/xior/blob/main/README.md
This TypeScript example demonstrates how to initialize an Xior instance and apply multiple plugins to enhance SSR application robustness. It showcases the integration of `error-retry`, `error-cache`, `dedupe`, and `throttle` plugins, illustrating their combined effect on handling failed requests, utilizing cached data, preventing redundant calls, and controlling request frequency.
```TypeScript
import xior, { XiorError as AxiosError } from 'xior';
import errorRetryPlugin from 'xior/plugins/error-retry';
import dedupePlugin from 'xior/plugins/dedupe';
import throttlePlugin from 'xior/plugins/throttle';
import errorCachePlugin from 'xior/plugins/error-cache';
// Setup
const http = axios.create({
baseURL: 'http://localhost:3000',
});
http.plugins.use(errorRetryPlugin());
http.plugins.use(errorCachePlugin());
http.plugins.use(dedupePlugin()); // Prevent same GET requests from occurring simultaneously.
http.plugins.use(throttlePlugin()); // Throttle same `GET` request in 1000ms
// 1. If `GET` data error, at least have chance to retry;
// 2. If retry still error, return the cache data(if have) to prevent page crash or show error page;
const res = await http.get('/api/get-data'); // these will retry if have error
if (res.fromCache) {
console.log(`the data from cahce`, res.cacheTime);
}
// 3. Dedupe the same `GET` requests, this will only sent 1 real request
await Promise.all([
http.get('/api/get-data-2'),
http.get('/api/get-data-2'),
http.get('/api/get-data-2'),
]);
// 4. Throttle the `GET` requests,
// we want throttle some larget data request in 10s, default is 1s
http.get('/api/get-some-big-data', { threshold: 10e3 });
// 5. If have cache data, return the cache data first,
// and run the real request in background
http.get('/api/get-some-big-data', { threshold: 10e3, useCacheFirst: true });
```
--------------------------------
### Mock GET Requests with Regular Expressions in Xior
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Demonstrates how to mock GET requests using a regular expression to match URLs. This allows for flexible matching and dynamic extraction of parameters, such as an ID from `config.url`, for custom response logic.
```ts
mock.onGet(/\/users\/\d+/).reply(function (config) {
// the actual id can be grabbed from config.url
return [200, {}];
});
```
--------------------------------
### Perform POST Requests with xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to make a POST request using a xior instance, including sending request body data, query parameters, and specifying response data types. This example also applies to PUT and PATCH methods.
```typescript
async function run() {
const { data: data3 } = await xiorInstance.post<{ field1: string; field2: number }>(
'/',
{ a: 1, b: '2' },
{
params: { id: 1 },
headers: {},
}
);
}
```
--------------------------------
### Implement Auth Token Refresh with xior-auth-refresh Community Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to integrate the `xior-auth-refresh` community plugin for automatic token refreshing. It includes installation instructions and a TypeScript example showing how to set up the interceptor with a custom refresh logic that handles 401 errors by obtaining a new token and retrying the failed request.
```sh
npm install xior-auth-refresh --save
# or
yarn add xior-auth-refresh
# or
pnpm add xior-auth-refresh
```
```ts
import xior from 'xior';
import createAuthRefreshInterceptor from 'xior-auth-refresh';
// Function that will be called to refresh authorization
const refreshAuthLogic = (failedRequest) =>
xior.post('https://www.example.com/auth/token/refresh').then((tokenRefreshResponse) => {
localStorage.setItem('token', tokenRefreshResponse.data.token);
failedRequest.response.config.headers['Authorization'] =
'Bearer ' + tokenRefreshResponse.data.token;
return Promise.resolve();
});
// Instantiate the interceptor
createAuthRefreshInterceptor(xior, refreshAuthLogic);
// Make a call. If it returns a 401 error, the refreshAuthLogic will be run,
// and the request retried with the new token
xior.get('https://www.example.com/restricted/area').then(/* ... */).catch(/* ... */);
```
--------------------------------
### Load Xior Throttle Plugin via jsDelivr CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to include the Xior core library and the throttle plugin using the jsDelivr CDN. This setup allows for direct use of Xior and its throttle plugin in a browser environment without a build step.
```html
```
--------------------------------
### Build Vue CLI Application for Production
Source: https://github.com/suhaotian/xior/blob/main/vue-cli-app/README.md
Compiles and minifies the Vue CLI application's source code into optimized static assets, ready for deployment to a production environment.
```Shell
yarn build
```
--------------------------------
### Mocking a GET Request with Specific Parameters
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Shows how to mock a GET request that includes specific query parameters. The mock is configured to respond only when the '/users' endpoint is requested with a `searchText` parameter set to 'John'.
```ts
import xior from 'xior';
import MockPlugin from 'xior/plugins/mock';
const instance = xior.create();
const mock = new MockPlugin(instance);
// 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);
});
```
--------------------------------
### Basic Usage of Xior Request Throttle Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to import and apply the `throttlePlugin` to an Xior instance. It illustrates throttling behavior for consecutive GET requests, custom throttle settings, and how to enable throttling for POST requests using the `enableThrottle` option or by marking them as `isGet`.
```typescript
import xior from 'xior';
import throttlePlugin from 'xior/plugins/throttle';
const http = xior.create();
http.plugins.use(
throttlePlugin({
onThrottle(config) {
console.log(`Throttle requests ${config.method} ${config.url}`);
},
})
);
http.get('/'); // make real http request
http.get('/'); // response from cache
http.get('/'); // response from cache
http.get('/', { throttle: 2e3 }); // custom throttle to 2 seconds
http.post('/'); // make real http request
http.post('/'); // make real http request
http.post('/'); // make real http request
http.post('/', null, {
enableThrottle: true,
}); // make real http request
http.post('/', null, {
enableThrottle: true,
}); // response from cache
http.post('/', null, {
enableThrottle: true,
}); // response from cache
// make post method as get method use `{isGet: true}`,
// useful when some API is get data but the method is `post`
http.post('/get', null, {
isGet: true,
}); // make real http request
http.post('/get', null, {
isGet: true,
}); // response from cache
http.post('/get', null, {
isGet: true,
}); // response from cache
```
--------------------------------
### Basic Usage of Xior Request Dedupe Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to import and apply the `dedupePlugin` to an `xior` instance. It demonstrates how the plugin prevents duplicate `GET` requests while allowing multiple `POST` requests to proceed.
```TypeScript
import xior from 'xior';
import dedupePlugin from 'xior/plugins/dedupe';
const http = xior.create();
http.plugins.use(
dedupePlugin({
onDedupe(config) {
console.log(`Dedupe ${config.method} ${config.url}`);
},
})
);
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
```
--------------------------------
### Basic Robots.txt Configuration for Full Access
Source: https://github.com/suhaotian/xior/blob/main/my-react-app/public/robots.txt
This snippet shows a minimal robots.txt file that grants full access to all web crawlers. The 'User-agent: *' directive applies the rule to all bots, and 'Disallow:' (empty) means no paths are disallowed, effectively allowing crawling of the entire site.
```Robots.txt
User-agent: *
Disallow:
```
--------------------------------
### Chain Multiple Mock Handlers in Xior
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Illustrates how to chain multiple `onGet` and `reply` calls to define mocks for different endpoints concisely. This approach streamlines the setup of multiple independent mock responses.
```ts
mock.onGet('/users').reply(200, users).onGet('/posts').reply(200, posts);
```
--------------------------------
### Basic Usage of Xior Error Retry Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to integrate and configure the `errorRetryPlugin` with `xior.create()`. It shows examples of setting `retryTimes`, custom `retryInterval` logic, and `onRetry` callback, as well as disabling retry for specific requests by setting `retryTimes: 0` or using `enableRetry`.
```typescript
import xior from 'xior';
import errorRetryPlugin from 'xior/plugins/error-retry';
const http = xior.create();
http.plugins.use(
errorRetryPlugin({
retryTimes: 3,
// retryInterval: 3000,
retryInterval(count, config, error) {
// if (error.response?.status === 500) return 10e3;
return count * 1e3;
},
onRetry(config, error, count) {
console.log(`${config.method} ${config.url} retry ${count} times`);
},
// enableRetry(config, error) {
// if ([401, 400].includes(error.response?.status)) { // no retry when status is 400 or 401
// return false;
// }
// // no return or return `undefined` here, will reuse the default `enableRetry` logic
// },
})
);
// if request error, max retry 3 times until success
http.get('/api1');
// if request error, will not retry, because `retryTimes: 0`
http.get('/api2', { retryTimes: 0 });
// if POST request error, will not retry
http.post('/api1');
// Use `enableRetry: true` to support post method, max retry 5 times until success
http.post('/api1', null, { retryTimes: 5, enableRetry: true });
```
--------------------------------
### Integrate xior with @tauri-apps/plugin-http in Tauri
Source: https://github.com/suhaotian/xior/blob/main/README.md
This snippet shows how to use the fetch implementation from @tauri-apps/plugin-http with xior within a Tauri application. It illustrates creating an xior instance with the Tauri fetch and making a simple GET request to retrieve data.
```ts
import { fetch } from '@tauri-apps/plugin-http';
import xior from 'xior';
export const http = xior.create({
baseURL: 'https://www.tauri.app',
fetch,
});
async function test() {
const { data } = await http.get('/');
return data;
}
```
--------------------------------
### Basic Usage of xior Cache Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to integrate and use the `cachePlugin` with xior for basic GET and POST request caching. It shows how to initialize the plugin with custom `cacheItems` and `cacheTime`, and how to manually enable or disable caching for specific requests, including checking if a response came from the cache.
```TypeScript
import xior from 'xior';
import cachePlugin from 'xior/plugins/cache';
const http = xior.create();
http.plugins.use(
cachePlugin({
cacheItems: 100,
cacheTime: 1e3 * 60 * 5,
})
);
http.get('/users'); // make real http request
http.get('/users'); // get cache from previous request
http.get('/users', { enableCache: false }); // disable cache manually and the real http request
http.post('/users'); // default no cache for post
// enable cache manually in post request
http.post('/users', { enableCache: true }); // make real http request
const res = await http.post('/users', { enableCache: true }); // get cache from previous request
if (res.fromCache) {
// if `fromCache` is true, means data from cache!
console.log('data from cache!', res.cacheKey, res.cacheTime);
}
```
--------------------------------
### Rejecting All GET Requests with HTTP 500
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Demonstrates how to configure the Xior mock plugin to reject all incoming GET requests with an HTTP 500 Internal Server Error status code, useful for simulating server-side errors.
```ts
mock.onGet().reply(500);
```
--------------------------------
### Implement Xior Interceptors for Data Encryption/Decryption
Source: https://github.com/suhaotian/xior/blob/main/README.md
This example demonstrates how to integrate encryption and decryption logic into `xior` requests and responses using interceptors. It shows how to encrypt request data before sending and decrypt response data upon reception.
```ts
import xior from 'xior';
import { SECRET, encrypt, decrypt } from './encryption';
export const instance = xior.create();
instance.interceptors.request.use((req) => {
req.headers['X'] = SECRET;
if (req.url && req.data) {
const result = JSON.stringify(req.data);
const blob = encrypt(result);
req.data = { blob };
}
return req;
});
instance.interceptors.response.use((res) => {
if (res.request.url && res.data?.blob) {
res.data = decrypt(res.data.blob);
try {
res.data = JSON.parse(res.data);
} catch (e) {
console.error(e);
}
}
return res;
});
```
--------------------------------
### Configure xior with node-fetch for custom fetch and proxy
Source: https://github.com/suhaotian/xior/blob/main/README.md
This example demonstrates how to use node-fetch with xior to provide a custom fetch implementation, including setting up http.Agent and https.Agent for persistent connections. It configures xior to use nodeFetch and a custom agent function to handle different protocols.
```sh
# For ESM module
npm install node-fetch
# For CommonJS module
# npm install node-fetch@v2.7.0
# npm install @types/node-fetch -D
```
```ts
import nodeFetch, { RequestInit as RequestInit_ } from 'node-fetch';
import http from 'node:http';
import https from 'node:https';
/** For TypeScript types **/
declare global {
interface RequestInit extends RequestInit_ {}
}
/** Create Agent **/
const httpAgent = new http.Agent({
keepAlive: true,
});
const httpsAgent = new https.Agent({
keepAlive: true,
});
const xiorInstance = xior.create({
baseURL: 'https://example.com',
fetch: nodeFetch,
// agent: httpAgent,
agent(_parsedURL) {
if (_parsedURL.protocol === 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
},
});
```
--------------------------------
### Lint and Fix Files in Vue CLI Project
Source: https://github.com/suhaotian/xior/blob/main/vue-cli-app/README.md
Runs ESLint to check for code style issues and potential errors in the Vue CLI project, automatically fixing many of them.
```Shell
yarn lint
```
--------------------------------
### Mock Any HTTP Method for a Specific URL in Xior
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Demonstrates using `mock.onAny('/foo').reply(200)` to mock all HTTP methods (GET, POST, PUT, DELETE, etc.) for a given URL. This provides a simple way to handle all requests to a specific path uniformly.
```ts
// mocks GET, POST, ... requests to /foo
mock.onAny('/foo').reply(200);
```
--------------------------------
### Access Xior Mock Handlers for Testing
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Describes how the `handlers` property of the Xior Mock Plugin provides access to currently registered xior response objects. This is useful for testing and verifying the setup of mock handlers.
```ts
import xior from 'xior';
import MockPlugin from 'xior/plugins/mock';
const instance = xior.create();
const mock = new MockPlugin(instance);
describe('Feature', () => {
it('resets the registered mock handlers', function () {
mock.onGet('/foo').reply(200);
assert.equal(mock.handlers['get'] && mock.handlers['get'].length > 0, true);
mock.reset();
assert.equal(mock.handlers['get'], undefined);
});
});
```
--------------------------------
### Download Files with Stream or Blob Response Types using Axios and Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to download files by setting the 'responseType' to 'stream' (for Node.js) or 'blob' (for browsers) using both Axios and Xior. Examples include saving the file to disk in Node.js and creating a downloadable link in the browser.
```ts
import axios from 'axios';
import fs from 'fs';
// GET request for remote image in Node.js
axios({
method: 'get',
url: 'https://bit.ly/2mTM3nY',
responseType: 'stream',
}).then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'));
});
// For browser
axios({
method: 'get',
url: 'https://bit.ly/2mTM3nY',
responseType: 'blob',
}).then(function (response) {
// create file link in browser's memory
const href = URL.createObjectURL(response.data);
// create "a" HTML element with href to file & click
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
// clean up "a" element & remove ObjectURL
document.body.removeChild(link);
URL.revokeObjectURL(href);
});
```
```ts
// Node.js
import xior from 'xior';
const axios = xior.create();
axios
.get('https://bit.ly/2mTM3nY', {
responseType: 'stream',
})
.then(async function ({ response, config }) {
const buffer = Buffer.from(await response.arrayBuffer());
return writeFile('ada_lovelace.jpg', buffer);
});
// For browser
xior
.get('https://d2l.ai/d2l-en.pdf', {
headers: {
Accept: 'application/pdf',
},
responseType: 'blob',
})
.then((res) => {
const { data: blob } = res;
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'filename.pdf';
document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
a.click();
a.remove(); //afterwards we remove the element again
});
```
--------------------------------
### Implement Auth Token Refresh with xior Built-in Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to use `xior`'s built-in `token-refresh` and `error-retry` plugins for handling authentication token expiration. This example sets up an interceptor to attach the token to requests, defines a `shouldRefresh` logic for 401/403 responses, and provides an asynchronous `refreshToken` function to acquire and store a new token.
```ts
import xior, { XiorResponse } from 'xior';
import errorRetry from 'xior/plugins/error-retry';
import setupTokenRefresh from 'xior/plugins/token-refresh';
const instance = xior.create();
const TOKEN_KEY = 'TOKEN';
function getToken() {
return localStorage.getItem(TOKEN_KEY);
}
function setToken(token: string) {
return localStorage.setItem(TOKEN_KEY, token);
}
function deleteToken() {
return localStorage.getItem(TOKEN_KEY);
}
instance.interceptors.request.use((config) => {
const token = getToken();
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
function shouldRefresh(response: XiorResponse) {
const token = getToken();
return Boolean(token && response?.status && [401, 403].includes(response.status));
}
instance.plugins.use(
errorRetry({
enableRetry: (config, error) => {
if (error?.response && shouldRefresh(error.response)) {
return true;
}
// return false
},
})
);
setupTokenRefresh(http, {
shouldRefresh,
async refreshToken(error) {
try {
const { data } = await http.post('/token/new');
if (data.token) {
setToken(data.token);
} else {
throw error;
}
} catch (e) {
// something wrong, delete old token
deleteToken();
return Promise.reject(error);
}
}
});
```
--------------------------------
### Throw Exception for Unmatched Requests in Xior Mock Plugin
Source: https://github.com/suhaotian/xior/blob/main/Mock-plugin.md
Illustrates configuring `MockPlugin` with `{ onNoMatch: 'throwException' }` to throw an error when a request is made without matching any mock handler. This feature is highly beneficial for debugging test setups and ensuring all expected requests are mocked.
```ts
const mock = new MockPlugin(instance, { onNoMatch: 'throwException' });
mock.onAny('/foo').reply(200);
axios.get('/unexistent-path');
// Exception message on console:
//
// Could not find mock for:
// {
// "method": "get",
// "url": "/unexistent-path"
// }
```
--------------------------------
### Create Configured Instances with Axios and Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Explains how to create reusable instances of Axios and Xior with common configurations such as 'baseURL', 'timeout', and default headers, promoting cleaner code and consistent behavior.
```ts
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' },
});
```
```ts
import axios from 'xior';
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' },
});
```
--------------------------------
### Loading Xior Mock Plugin via CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides HTML script tags to load the Xior core library and the mock plugin from popular CDNs (jsDelivr and unpkg). It includes a basic JavaScript snippet to verify the Xior version and initialize the mock plugin.
```html
```
```html
```
--------------------------------
### Simulating Upload Progress with Xior and Progress Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to integrate and use the `uploadDownloadProgressPlugin` with Xior. It shows creating an Xior instance, applying the plugin, and making a `POST` request with `FormData` while configuring `progressDuration` and `onUploadProgress` callback.
```typescript
import xior from 'xior';
import uploadDownloadProgressPlugin from 'xior/plugins/progress';
const http = xior.create({});
http.plugins.use(uploadDownloadProgressPlugin());
const formData = FormData();
formData.append('file', fileObject);
formData.append('field1', 'val1');
formData.append('field2', 'val2');
http.post('/upload', formData, {
// simulate upload progress to 99% in 10 seconds, default is 5 seconds
progressDuration: 10 * 1000,
onUploadProgress(e) {
console.log(`Upload progress: ${e.progress}%`);
},
// onDownloadProgress(e) {
// console.log(`Download progress: ${e.progress}%`);
// },
});
```
--------------------------------
### Load Xior Throttle Plugin via unpkg CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to include the Xior core library and the throttle plugin using the unpkg CDN. This method provides an alternative for direct browser usage, similar to jsDelivr.
```html
```
--------------------------------
### Loading Xior Progress Plugin via CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides HTML script tags to load the Xior core library and the progress plugin from popular CDNs (jsDelivr and unpkg). It includes a basic JavaScript snippet to verify the Xior version and apply the progress plugin.
```html
```
```html
```
--------------------------------
### Handle stream and original fetch responses with xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
This example explains that when responseType is set to 'stream', 'document', 'custom', or 'original', xior returns the original fetch response object in res.response, and res.data will be undefined. It also provides an example of how to process a stream response using response.body.getReader().
```ts
fetch('https://exmaple.com/some/api').then((response) => {
console.log(response);
});
// same with
xior.get('https://exmaple.com/some/api', { responseType: 'stream' }).then((res) => {
console.log(res.response); // But res.data will be undefined
});
import xior from 'xior';
const http = xior.create({ baseURL });
const { response } = await http.post<{ file: any; body: Record }>(
'/stream/10',
null,
{ responseType: 'stream' }
);
const reader = response.body!.getReader();
let chunk;
for await (chunk of readChunks(reader)) {
console.log(`received chunk of size ${chunk.length}`);
}
```
--------------------------------
### Create a xior Instance
Source: https://github.com/suhaotian/xior/blob/main/README.md
Illustrates how to create a custom xior instance with a base URL and default headers, allowing for reusable configurations for API calls.
```typescript
import xior from 'xior';
export const xiorInstance = xior.create({
baseURL: 'https://apiexampledomain.com/api',
headers: {
// put your common custom headers here
},
});
```
--------------------------------
### Cancel Xior Requests with AbortController
Source: https://github.com/suhaotian/xior/blob/main/README.md
This example shows how to cancel an ongoing `xior` request using the `AbortController` API. A custom error can be passed to the `abort()` method to provide more context for the cancellation.
```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
```
--------------------------------
### Make Requests using a Configuration Object with Axios and Xior
Source: https://github.com/suhaotian/xior/blob/main/README.md
Shows how to make requests by passing a configuration object to the main 'axios' function (Axios) or 'xior.request' method (Xior), specifying the HTTP method and parameters.
```ts
import axios from 'axios';
await axios({ method: 'get', params: { a: 1 } });
```
```ts
import xior from 'xior';
const axios = xior.create();
await axios.request({ method: 'get', params: { a: 1 } });
```
--------------------------------
### Basic Xior Plugin Integration
Source: https://github.com/suhaotian/xior/blob/main/README.md
This snippet illustrates the fundamental approach to adding various plugins to an Xior instance. It shows how to import specific plugins like `error-retry`, `throttle`, `cache`, and `uploadDownloadProgress` and register them with the Xior client using the `http.plugins.use()` method, providing a foundation for extending Xior's capabilities.
```TypeScript
import xior from 'xior';
import errorRetryPlugin from 'xior/plugins/error-retry';
import throttlePlugin from 'xior/plugins/throttle';
import cachePlugin from 'xior/plugins/cache';
import uploadDownloadProgressPlugin from 'xior/plugins/progress';
const http = xior.create();
http.plugins.use(errorRetryPlugin());
http.plugins.use(throttlePlugin());
http.plugins.use(cachePlugin());
http.plugins.use(uploadDownloadProgressPlugin());
```
--------------------------------
### Load Xior Error Retry Plugin via unpkg CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides HTML script tags to load the Xior core library and the error retry plugin from unpkg CDN. Includes a basic JavaScript snippet demonstrating how to use the plugin after loading it in a browser environment.
```html
```
--------------------------------
### Import xior Built-in Helper Functions
Source: https://github.com/suhaotian/xior/blob/main/README.md
Lists and imports various utility functions provided by `xior` that can be useful for common tasks. These helpers include functions for parameter encoding, deep merging, delaying execution, URL manipulation, error checking, and undefined value trimming.
```ts
import lru from 'tiny-lru';
import {
encodeParams,
merge as deepMerge,
delay as sleep,
buildSortedURL,
isAbsoluteURL,
joinPath,
isXiorError,
trimUndefined,
Xior
} from 'xior';
```
--------------------------------
### Mocking POST Requests with Xior Mock Plugin
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to use the `MockPlugin` to intercept and mock `POST` requests. It covers mocking a general `POST /users` request, a conditional mock based on URL parameters, and another conditional mock based on the request body.
```typescript
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);
});
```
--------------------------------
### Load Xior Error Retry Plugin via jsDelivr CDN
Source: https://github.com/suhaotian/xior/blob/main/README.md
Provides HTML script tags to load the Xior core library and the error retry plugin from jsDelivr CDN. Includes a basic JavaScript snippet demonstrating how to use the plugin after loading it in a browser environment.
```html
```
--------------------------------
### Upload Files with xior and Progress Tracking
Source: https://github.com/suhaotian/xior/blob/main/README.md
Demonstrates how to upload files using `FormData` with xior, including the integration of the `xior/plugins/progress` plugin to monitor upload progress, similar to Axios.
```typescript
import Xior from 'xior';
import uploadDownloadProgressPlugin from 'xior/plugins/progress';
const http = Xior.create({});
http.plugins.use(
uploadDownloadProgressPlugin({
progressDuration: 5 * 1000,
})
);
const formData = FormData();
formData.append('file', fileObject);
formData.append('field1', 'val1');
formData.append('field2', 'val2');
http.post('/upload', formData, {
onUploadProgress(e) {
console.log(`Upload progress: ${e.progress}%`);
},
// progressDuration: 10 * 1000
});
```
--------------------------------
### Configure xior with undici for custom fetch and proxy
Source: https://github.com/suhaotian/xior/blob/main/README.md
This snippet demonstrates how to integrate undici's fetch implementation with xior to enable proxy support or custom fetch behavior. It shows creating an Agent for connection pooling and passing undiciFetch and the dispatcher to xior.create().
```sh
npm install undici
```
```ts
import { fetch as undiciFetch, FormData, Agent, type RequestInit as RequestInit_ } from 'undici';
/** For TypeScript types **/
declare global {
interface RequestInit extends RequestInit_ {}
}
/** Create Agent **/
const agent = new Agent({
connections: 10,
});
const xiorInstance = xior.create({
baseURL: 'https://example.com',
fetch: undiciFetch,
dispatcher: agent,
});
```