diff --git a/README.md b/README.md
index 86e2738..25d30c3 100644
--- a/README.md
+++ b/README.md
@@ -1,38 +1,39 @@
# Axios Multi API
+Fast, lightweight and reusable data fetching
+
[npm-url]: https://npmjs.org/package/axios-multi-api
[npm-image]: http://img.shields.io/npm/v/axios-multi-api.svg
-[![NPM version][npm-image]][npm-url] [![Blazing Fast](https://badgen.now.sh/badge/speed/blazing%20%F0%9F%94%A5/green)](https://github.com/MattCCC/axios-multi-api) [![Code Coverage](https://badgen.now.sh/badge/coverage/94.53/blue)](https://github.com/MattCCC/axios-multi-api) [![npm downloads](https://img.shields.io/npm/dm/axios-multi-api.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios-multi-api) [![install size](https://packagephobia.now.sh/badge?p=axios-multi-api)](https://packagephobia.now.sh/result?p=axios-multi-api)
+[![NPM version][npm-image]][npm-url] [![Blazing Fast](https://badgen.now.sh/badge/speed/blazing%20%F0%9F%94%A5/green)](https://github.com/MattCCC/axios-multi-api) [![Code Coverage](https://badgen.now.sh/badge/coverage/94.53/blue)](https://github.com/MattCCC/axios-multi-api) [![npm downloads](https://img.shields.io/npm/dm/axios-multi-api.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios-multi-api) [![gzip size](https://img.shields.io/bundlephobia/minzip/axios-multi-api)](https://bundlephobia.com/result?p=axios-multi-api)
## Why?
-To handle many API endpoints and calls in a simple, declarative fashion. It aims to provide a possibility to additional fetching features with absolutely minimal code footprint.
-
-Oftentimes projects require complex APIs setups, middlewares and another stuff to accommodate a lot of API requests. This package simplifies API handling to the extent that developers can focus on operating on the fetched data from their APIs rather than on complex setups. You can set up multiple API fetchers for different sets of APIs from different services. It provides much better scalability for many projects.
+Managing multiple API endpoints can be complex and time-consuming. `axios-multi-api` simplifies this process by offering a straightforward, declarative approach to API handling using Repository Pattern. It reduces the need for extensive setup and middlewares, allowing developers to focus on data manipulation and application logic.
-> If you’re new to Axios, please check out [this handy Axios readme](https://github.com/axios/axios)
+**Key Benefits:**
-Package was originally written to accommodate many API requests in an orderly fashion.
+**✅ Simplicity:** Minimal code footprint for managing extensive APIs.
+**✅ Productivity:** Streamlines API interactions, enhancing developer efficiency.
+**✅ Scalability:** Easily scales from a few endpoints to complex API networks.
## Features
-- Fast, lightweight and reusable data fetching
-- **Pure JavaScript, framework independent**
-- **Easily manage large applications with many API endpoints**
-- **Native fetch() support by default, so Axios can be skipped**
-- Smart error retry with exponential backoff
-- Error handling - global and per request
-- Automatic cancellation of previous requests using `AbortController`
-- Global and per request timeouts
-- Multiple fetching strategies when requests fail - promise rejection, silently hang promise, provide default response,
-- Dynamic URLs support e.g. `/user/:userId`
-- Multiple requests chaining (using promises)
-- All Axios options are supported
-- 100% performance oriented solution
-- **Browsers and Node 18+ compatible**
-- **Fully TypeScript compatible**
-- **Very lightweight, only a few KBs, gziped**
+- **100% Performance-Oriented**: Optimized for speed and efficiency, ensuring fast and reliable API interactions.
+- **Fully TypeScript Compatible**: Enjoy full TypeScript support for better development experience and type safety.
+- **Smart Error Retry**: Features exponential backoff for intelligent error handling and retry mechanisms.
+- **Dynamic URLs Support**: Easily manage routes with dynamic parameters, such as `/user/:userId`.
+- **Native `fetch()` Support**: Uses the modern `fetch()` API by default, eliminating the need for Axios.
+- **Global and Per Request Error Handling**: Flexible error management at both global and individual request levels.
+- **Automatic Request Cancellation**: Utilizes `AbortController` to cancel previous requests automatically.
+- **Global and Per Request Timeouts**: Set timeouts globally or per request to prevent hanging operations.
+- **Multiple Fetching Strategies**: Handle failed requests with various strategies - promise rejection, silent hang, soft fail, or default response.
+- **Multiple Requests Chaining**: Easily chain multiple requests using promises for complex API interactions.
+- **Supports All Axios Options**: Fully compatible with all Axios configuration options for seamless integration.
+- **Lightweight**: Minimal footprint, only a few KBs when gzipped, ensuring quick load times.
+- **Framework Independent**: Pure JavaScript solution, compatible with any framework or library.
+- **Browser and Node 18+ Compatible**: Works flawlessly in both modern browsers and Node.js environments.
+- **Custom Interceptors**: Includes `onRequest`, `onResponse`, and `onError` interceptors for flexible request and response handling.
Please open an issue for future requests.
@@ -46,41 +47,57 @@ Using NPM:
npm install axios-multi-api
```
-Using yarn:
+Using Pnpm:
+
+```bash
+pnpm install axios-multi-api
+```
+
+Using Yarn:
```bash
yarn add axios-multi-api
```
-The native `fetch()` is used by default. If you want to use Axios, install it separately e.g. by running `npm install axios`, and then pass the import to the `createApiFetcher()` function. Check advanced example for more details.
+### Standalone usage
+
+```typescript
+import { fetchf } from 'axios-multi-api';
+
+const { data } = await fetchf('/api/user-details');
+```
+
+### Multiple API Endpoints
```typescript
import { createApiFetcher } from 'axios-multi-api';
const api = createApiFetcher({
apiUrl: 'https://example.com/api',
+ strategy: 'softFail', // no try/catch required
endpoints: {
getUser: {
+ method: 'get',
url: '/user-details',
},
},
});
// Make API GET request to: http://example.com/api/user-details?userId=1&ratings[]=1&ratings[]=2
-const { data } = await api.getUser({ userId: 1, ratings: [1, 2] });
+const { data, error } = await api.getUser({ userId: 1, ratings: [1, 2] });
```
-Standalone usage: (without endpoints):
+Note:
-```typescript
-import { fetchf } from 'axios-multi-api';
+> The native `fetch()` is used by default. If you want to use Axios, install it separately (e.g. `npm install axios`), and then pass the import to the `createApiFetcher()` function. Check examples for more details.
-const { data } = await fetchf('/api/user-details');
-```
+## ✔️ Easy Integration with React and Other Libraries
+
+`axios-multi-api` is designed to seamlessly integrate with popular libraries like [React Query](https://react-query-v3.tanstack.com/guides/queries) and [SWR](https://swr.vercel.app/). Whether you're using React Query or SWR, you can effortlessly manage API requests with minimal setup.
-## ✔️ Easy to use with React and other libraries
+### 📦 Using with React Query
-You could use [React Query](https://react-query-v3.tanstack.com/guides/queries) hooks with API handler:
+Integrate `axios-multi-api` with React Query to streamline your data fetching:
```typescript
import { createApiFetcher } from 'axios-multi-api';
@@ -99,77 +116,275 @@ export const useProfile = ({ id }) => {
};
```
-## ✔️ API
+### 🌊 Using with SWR
-### api.myEndpoint(queryParams, urlPathParams, requestConfig)
+Combine `axios-multi-api` with SWR for efficient data fetching and caching:
-Where "myEndpoint" is the name of your endpoint from `endpoints` object passed to the `createApiFetcher()`.
-
-`queryParams` / `payload` (optional) - Query Parameters or Body Payload for POST requests.
-
-First argument of API functions is an object with query params for `GET` requests, or with a data payload for `POST` alike requests. Other request types are supported as well. For `POST` alike requests you may occasionally want to use both query params and payload. In such case, use this argument as query params and pass the payload as 3rd argument `requestConfig.body` or `requestConfig.data` (for Axios)
-
-Query params accepts strings, numbers, and even arrays, so you pass { foo: [1, 2] } and it will become: foo[]=1&foo[]=2 automatically.
+```typescript
+import { createApiFetcher } from 'axios-multi-api';
+import useSWR from 'swr';
-`urlPathParams` (optional) - Dynamic URL Path Parameters
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api',
+ endpoints: {
+ getProfile: {
+ url: '/profile/:id',
+ },
+ },
+});
-It gives possibility to modify URLs structure in a declarative way. In our example `/user-details/update/:userId` will become `/user-details/update/1` when API request will be made.
+export const useProfile = ({ id }) => {
+ const fetcher = () => api.getProfile({ id });
-`requestConfig` (optional) - Request Configuration to overwrite global config in case
+ const { data, error } = useSWR(['profile', id], fetcher);
-To have more granular control over specific endpoints you can pass Axios compatible [Request Config](https://github.com/axios/axios#request-config) for particular endpoint. You can also use Global Settings like `cancellable` or `strategy` mentioned below.
+ return {
+ profile: data,
+ isLoading: !error && !data,
+ isError: error,
+ };
+};
+```
-### api.getInstance()
+Check examples below for more integrations with other libraries.
-When API handler is firstly initialized, a new Axios instance is created. You can call `api.getInstance()` if you want to get that instance directly, for example to add some interceptors.
+## ✔️ API
-### api.config
+### `fetchf()`
-You can access `api.config` directly, so to modify global headers, and other settings on fly. Please mind it is a property, not a function.
+`fetchf()` is a functional wrapper for `fetch()`. It integrates seamlessly with the retry mechanism and error handling improvements. Unlike the traditional class-based approach, `fetchf()` can be used directly as a function, simplifying the usage and making it easier to integrate with functional programming styles.
-### api.endpoints
+```typescript
+import { fetchf } from 'axios-multi-api';
-You can access `api.endpoints` directly, so to modify endpoints list. It can be useful if you want to append or remove global endpoints. Please mind it is a property, not a function.
+const { data, error } = await fetchf('/api/user-details', {
+ timeout: 5000,
+ cancellable: true,
+ retry: { retries: 3, delay: 2000 },
+ // All other fetch() settings work as well...
+});
+```
-## ✔️ fetchf() - improved native fetch() wrapper
+> The fetchf() makes requests independently from createApiFetcher()
-The `axios-multi-api` wraps the endpoints around and automatically uses `fetchf()` under the hood. However, you can use `fetchf()` directly just like you use `fetch()`.
+**Challenges with Native Fetch:**
-### Improvements to native fetch
+- **Error Status Handling:** Fetch does not throw errors for HTTP error statuses, making it difficult to distinguish between successful and failed requests based on status codes alone.
+- **Error Visibility:** Error responses with status codes like 404 or 500 are not automatically propagated as exceptions, which can lead to inconsistent error handling.
To address these challenges, the `fetchf()` provides several enhancements:
1. **Consistent Error Handling:**
- - The `createApiFetcher()` and `fetchf()` both ensure that HTTP error statuses (e.g., 404, 500) are treated as errors. This is achieved by wrapping `fetch()` in a way that checks the response status and throws an exception if the `ok` property is `false`.
+ - In JavaScript, the native `fetch()` function does not reject the Promise for HTTP error statuses such as 404 (Not Found) or 500 (Internal Server Error). Instead, `fetch()` resolves the Promise with a `Response` object, where the `ok` property indicates the success of the request. If the request encounters a network error or fails due to other issues (e.g., server downtime), `fetch()` will reject the Promise.
- This approach aligns error handling with common practices and makes it easier to manage errors consistently.
2. **Enhanced Retry Mechanism:**
- **Retry Configuration:** You can configure the number of retries, delay between retries, and exponential backoff for failed requests. This helps to handle transient errors effectively.
- **Custom Retry Logic:** The `shouldRetry` asynchronous function allows for custom retry logic based on the error and attempt count, providing flexibility to handle different types of failures.
+ - **Retry Conditions:** Errors are only retried based on configurable retry conditions, such as specific HTTP status codes or error types.
3. **Improved Error Visibility:**
- **Error Wrapping:** The `createApiFetcher()` and `fetchf()` wrap errors in a custom `RequestError` class, which provides detailed information about the request and response, similarly to what Axios does. This makes debugging easier and improves visibility into what went wrong.
- - **Retry Conditions:** Errors are only retried based on configurable retry conditions, such as specific HTTP status codes or error types.
-4. **Functional `fetchf()` Wrapper:**
- - **Wrapper Function:** `fetchf()` is a functional wrapper for `fetch()`. It integrates seamlessly with the retry mechanism and error handling improvements.
- - **No Class Dependency:** Unlike the traditional class-based approach, `fetchf()` can be used directly as a function, simplifying the usage and making it easier to integrate with functional programming styles.
+4. **Extended settings:**
+ - Check Settings table for more information about all settings.
-### Improved Fetch Error Handling
+### `createApiFetcher()`
-In JavaScript, the native `fetch()` function does not reject the Promise for HTTP error statuses such as 404 (Not Found) or 500 (Internal Server Error). Instead, `fetch()` resolves the Promise with a `Response` object, where the `ok` property indicates the success of the request. If the request encounters a network error or fails due to other issues (e.g., server downtime), `fetch()` will reject the Promise.
+`createApiFetcher()` is a powerful factory function for creating API fetchers with advanced features. It provides a convenient way to configure and manage multiple API endpoints using a declarative approach. This function offers integration with retry mechanisms, error handling improvements, and other advanced configurations. Unlike traditional methods, `createApiFetcher()` allows you to set up and use API endpoints efficiently with minimal boilerplate code.
-**Challenges with Native Fetch:**
+#### Usage Example
-- **Error Status Handling:** Fetch does not throw errors for HTTP error statuses, making it difficult to distinguish between successful and failed requests based on status codes alone.
-- **Error Visibility:** Error responses with status codes like 404 or 500 are not automatically propagated as exceptions, which can lead to inconsistent error handling.
+```typescript
+import { createApiFetcher } from 'axios-multi-api';
+
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api',
+ endpoints: {
+ getUserDetails: {
+ url: '/user-details',
+ method: 'GET',
+ retry: { retries: 3, delay: 2000 },
+ timeout: 5000,
+ cancellable: true,
+ strategy: 'softFail',
+ },
+ updateUser: {
+ url: '/update-user',
+ method: 'POST',
+ retry: { retries: 2, delay: 1000 },
+ },
+ // Define more endpoints as needed
+ },
+});
+
+// Example usage
+const { data, error } = await api.getUserDetails();
+```
+
+The `const api` methods and properties are described below:
+
+#### `api.myEndpoint(queryParams, urlPathParams, requestConfig)`
+
+Where "myEndpoint" is the name of your endpoint from `endpoints` object passed to the `createApiFetcher()`.
+
+1. **`queryParams`** / **`payload`** (optional) - Query Parameters or Body Payload for POST requests.
+ First argument of API functions is an object with query params for `GET` requests, or with a data payload for `POST` alike requests. Other request types are supported as well. For `POST` alike requests you may occasionally want to use both query params and payload. In such case, use this argument as query params and pass the payload as 3rd argument `requestConfig.body` or `requestConfig.data` (for Axios)
+ Query params accepts strings, numbers, and even arrays, so you pass { foo: [1, 2] } and it will become: foo[]=1&foo[]=2 automatically.
+
+2. **`urlPathParams`** (optional) - Dynamic URL Path Parameters
+ It gives possibility to modify URLs structure in a declarative way. In our example `/user-details/update/:userId` will become `/user-details/update/1` when API request will be made.
+
+3. **`requestConfig`** (optional) - Request Configuration to overwrite global config in case
+ To have more granular control over specific endpoints you can pass Axios compatible [Request Config](https://github.com/axios/axios#request-config) for particular endpoint. You can also use Global Settings like `cancellable` or `strategy` and others mentioned below.
+
+Returns: **`response`** or **`data`** object, depending on `flattenResponse` setting:
+
+##### Response Object without `flattenResponse` (default)
+
+When `flattenResponse` is disabled, the response object includes a more detailed structure, encapsulating various aspects of the response:
+
+- **`data`**:
+
+ - Contains the actual data returned from the API request.
+
+- **`error`**:
+
+ - An object with details about any error that occurred or `null` otherwise.
+ - **`name`**: The name of the error (e.g., 'ResponseError').
+ - **`message`**: A descriptive message about the error.
+ - **`status`**: The HTTP status code of the response (e.g., 404, 500).
+ - **`statusText`**: The HTTP status text of the response (e.g., 'Not Found', 'Internal Server Error').
+ - **`request`**: Details about the HTTP request that was sent (e.g., URL, method, headers).
+ - **`config`**: The configuration object used for the request, including URL, method, headers, and query parameters.
+ - **`response`**: The full response object received from the server, including all headers and body.
+
+- **`config`**:
+
+ - The configuration object with all settings used for the request, including URL, method, headers, and query parameters.
+
+- **`request`**:
+
+ - An alias for `config`.
+
+- **`headers`**:
+ - The response headers returned by the server, such as content type and caching information returned as simple key-value object.
+
+##### Response Object with `flattenResponse`
+
+When the `flattenResponse` option is enabled, the `data` from the API response is directly exposed as the top-level property of the response object. This simplifies access to the actual data, as it is not nested within additional response metadata.
+
+##### Key Points
+
+- **With `flattenResponse` Enabled**:
+
+ - **`data`**: Directly contains the API response data.
+
+- **With `flattenResponse` Disabled**:
+ - **`data`**: Contains the API response data nested within a broader response structure.
+ - **`error`**: Provides detailed information about any errors encountered.
+ - **`config`**: Shows the request configuration.
+ - **`request`**: Details the actual HTTP request sent.
+ - **`headers`**: Includes the response headers from the server.
+
+The `flattenResponse` option provides a more streamlined response object by placing the data directly at the top level, while disabling it gives a more comprehensive response structure with additional metadata.
+
+#### `api.config`
+
+You can access `api.config` property directly, so to modify global headers, and other settings on fly. Please mind it is a property, not a function.
+
+#### `api.endpoints`
+
+You can access `api.endpoints` property directly, so to modify endpoints list. It can be useful if you want to append or remove global endpoints. Please mind it is a property, not a function.
+
+#### `api.getInstance()`
+
+When API handler is firstly initialized, a new custom `fetcher` instance is created. You can call `api.getInstance()` if you want to get that instance directly, for example to add some interceptors. The instance of `fetcher` is created using `fetcher.create()` functions. Your fetcher can include anything. It will be triggered instead of native fetch() that is available by default.
+
+#### `api.request()`
+
+The `api.request()` helper function is a versatile method provided for making API requests with customizable configurations. It allows you to perform HTTP requests to any endpoint defined in your API setup and provides a straightforward way to handle queries, path parameters, and request configurations dynamically.
+
+##### Example
+
+```typescript
+import { createApiFetcher } from 'axios-multi-api';
+
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api',
+ endpoints: {
+ getUserDetails: {
+ url: '/user-details/:id',
+ method: 'GET',
+ },
+ updateUser: {
+ url: '/update-user',
+ method: 'POST',
+ },
+ // Define more endpoints as needed
+ },
+});
+
+// Using api.request to make a GET request
+const { data, error } = await api.request(
+ 'getUserDetails',
+ null, // no Query Params passed
+ {
+ id: '123', // URL Path Param :id
+ },
+);
+
+// Using api.request to make a POST request
+const { data, error } = await api.request('updateUser', {
+ name: 'John Doe', // Data Payload
+});
+
+// Using api.request to make a GET request to an external API
+const { data, error } = await api.request('https://example.com/api/user', {
+ name: 'John Smith', // Query Params
+});
+```
+
+## ✔️ Settings (Request Config)
+
+Global settings are passed to `createApiFetcher()` function. Settings that are global only are market with star `*` next to setting name.
+
+Almost all settings can be passed on per-request basis in the third argument of endpoint function, for example `api.getUser({}, {}, { /* Request Config */ })`.
+
+You can also pass all `fetch()` settings, or if you use Axios, you can pass all [Axios Request Config](https://github.com/axios/axios#request-config) settings.
+
+| Setting | Type | Default | Description |
+| ----------------- | ------------------ | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| apiUrl \* | string | | Your API base url. |
+| endpoints \* | object | | List of your endpoints. Each endpoint accepts all these settings. They can be set globally or per-endpoint when they are called. |
+| fetcher \* | AxiosStatic | fetch | The native `fetch()` is used by default. Axios instance imported from axios package can be used otherwise. Leave as is, if you do not intend to use Axios. |
+| strategy | string | reject | Error handling strategies - basically what to return when an error occurs. It can be a default data, promise can be hanged (nothing would be returned) or rejected so to use try/catch.
`reject` - Promises are rejected, and global error handling is triggered. Requires try/catch for handling.
`softFail` - returns a response object with additional properties such as `data`, `error`, `config`, `request`, and `headers` when an error occurs. This approach avoids throwing errors, allowing you to handle error information directly within the response object without the need for try/catch blocks.
`defaultResponse` - returns default response specified in case of an error. Promise will not be rejected. It could be used in conjuction with `flattenResponse` and as `defaultResponse: {}` so to provide a sensible defaults.
`silent` - hangs the promise silently on error, useful for fire-and-forget requests without the need for try/catch. In case of an error, the promise will never be resolved or rejected, and any code after will never be executed. The requests could be dispatched within an asynchronous wrapper functions that do not need to be awaited. If used properly, it prevents excessive usage of try/catch or additional response data checks everywhere. You can use it in combination with `onError` to handle errors separately. |
+| cancellable | boolean | false | If `true`, any previous requests to same API endpoint will be cancelled, if a subsequent request is made meanwhile. This helps you avoid unnecessary requests to the backend. |
+| rejectCancelled | boolean | false | If `true` and request is set to `cancellable`, a cancelled requests' promise will be rejected. By default, instead of rejecting the promise, `defaultResponse` is returned. |
+| flattenResponse | boolean | false | Flatten nested response data, so you can avoid writing `response.data.data` and obtain response directly. Response is flattened when there is a "data" within response "data", and no other object properties set. |
+| defaultResponse | any | null | Default response when there is no data or when endpoint fails depending on the chosen `strategy` |
+| timeout | int | 30000 | You can set a request timeout for all requests or particular in milliseconds. |
+| onRequest | function(config) | | You can specify a function that will be triggered before the request is sent. The request configuration object will be sent as the first argument of the function. This is useful for modifying request parameters, headers, etc. |
+| onResponse | function(response) | | You can specify a function that will be triggered when the endpoint successfully responds. The full Response Object is sent as the first argument of the function. This is useful for handling the response data, parsing, and error handling based on status codes. |
+| onError | function(error) | | You can specify a function or class that will be triggered when endpoint fails. If it's a class it should expose a `process` method. When using native fetch(), the full Response Object is sent as a first argument of the function. In case of Axios, AxiosError object is sent. |
+| logger | object | | You can additionally specify logger object with your custom logger to automatically log the errors to the console. It should contain at least `error` and `warn` functions. `console.log` is used by default. |
+| method | string | get | Default request method e.g. GET, POST, DELETE, PUT etc. |
+| url | string | | URL path e.g. /user-details/get |
+| urlPathParams | object | {} | An object representing URL path parameters. These parameters are used to dynamically replace placeholders in the URL path. For example, if your URL contains a placeholder like `/users/:userId`, you can provide an object with the `userId` key to replace that placeholder with an actual value. The keys in the `urlPathParams` object should match the placeholders in the URL. This allows for dynamic URL construction based on runtime values. |
+| retry | object | | The object with retry settings available below. |
+| retry.retries | number | 0 | The number of times to retry the request in case of failure. If set to `0` (default), no retries will be attempted. |
+| retry.delay | number | 1000 | The initial delay (in milliseconds) between retry attempts. |
+| retry.backoff | number | 1.5 | The backoff factor to apply to the delay between retries. For example, if the delay is 100ms and the backoff is 1.5, the next delay will be 150ms, then 225ms, and so on. |
+| retry.maxDelay | number | 30000 | The maximum delay (in milliseconds) between retry attempts. |
+| retry.retryOn | array | [408, 409, 425, 429, 500, 502, 503, 504] | An array of HTTP status codes on which to retry the request. Default values include: 408 (Request Timeout), 409 (Conflict), 425 (Too Early), 429 (Too Many Requests), 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout). |
+| retry.shouldRetry | async function | | A custom asynchronous function to determine whether to retry the request. It receives two arguments: `error` (the error object) and `attempts` (the number of attempts made so far). |
## ✔️ Retry Mechanism
-The exposed `fetchf()` and `createApiFetcher()` function include a built-in retry mechanism to handle transient errors and improve the reliability of network requests. This mechanism automatically retries requests when certain conditions are met, providing robustness in the face of temporary failures. Below is an overview of how the retry mechanism works and how it can be configured.
+The exposed `fetchf()` and `createApiFetcher()` functions include a built-in retry mechanism to handle transient errors and improve the reliability of network requests. This mechanism automatically retries requests when certain conditions are met, providing robustness in the face of temporary failures. Below is an overview of how the retry mechanism works and how it can be configured.
### Configuration
@@ -211,39 +426,35 @@ The retry mechanism is configured via the `retry` option when instantiating the
Check Examples section below for more information.
-## ✔️ Settings (Request Config)
-
-Global settings are passed to `createApiFetcher()` function. Settings that are global only are market with star `*` next to setting name.
-
-Almost all settings can be passed on per-request basis in the third argument of endpoint function, for example `api.getUser({}, {}, { /* Request Config */ })`.
-
-You can also pass all `fetch()` settings, or if you use Axios, you can pass all [Axios Request Config](https://github.com/axios/axios#request-config) settings.
-
-| Setting | Type | Default | Description |
-| ----------------- | ------------------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| apiUrl \* | string | | Your API base url. |
-| endpoints \* | object | | List of your endpoints. Each endpoint accepts all these settings. They can be set globally or per-endpoint when they are called. |
-| fetcher \* | AxiosStatic | fetch | The native `fetch()` is used by default. Axios instance imported from axios package can be used otherwise. Leave as is, if you do not intend to use Axios. |
-| strategy | string | reject | Error handling strategies - basically what to return when an error occurs. It can be a default data, promise can be hanged (nothing would be returned) or rejected so to use try/catch.
Available: `silent`, `reject`, `defaultResponse`.
`reject` - standard way - simply rejects the promise. Global error handling is triggered right before the rejection. You need to set try/catch to catch errors.
`defaultResponse` in case of an error, it returns default response specified in global `defaultResponse` or per endpoint `defaultResponse` setting. Promise will not be rejected! Data from default response will be returned instead. It could be used together with object destructuring by setting `defaultResponse: {}` so to provide a responsible defaults.
`silent` can be used for requests that are dispatched within asynchronous wrapper functions that are not awaited. If a request fails, promise will silently hang and no action will be performed. In case of an error, the promise will never be resolved or rejected, and any code after will never be executed. If used properly it saves developers from try/catch or additional response data checks everywhere. You can use is in combination with `onError` so to handle errors globally. |
-| cancellable | boolean | false | If `true`, any previous requests to same API endpoint will be cancelled, if a subsequent request is made meanwhile. This helps you avoid unnecessary requests to the backend. |
-| rejectCancelled | boolean | false | If `true` and request is set to `cancellable`, a cancelled requests' promise will be rejected. By default, instead of rejecting the promise, `defaultResponse` is returned. |
-| flattenResponse | boolean | false | Flatten nested response data, so you can avoid writing `response.data.data` and obtain response directly. Response is flattened when there is a "data" within response "data", and no other object properties set. |
-| defaultResponse | any | null | Default response when there is no data or when endpoint fails depending on the chosen `strategy` |
-| timeout | int | 30000 | You can set a request timeout for all requests or particular in milliseconds. |
-| onRequest | function(config) | | You can specify a function that will be triggered before the request is sent. The request configuration object will be sent as the first argument of the function. This is useful for modifying request parameters, headers, etc. |
-| onResponse | function(response) | | You can specify a function that will be triggered when the endpoint successfully responds. The full Response Object is sent as the first argument of the function. This is useful for handling the response data, parsing, and error handling based on status codes. |
-| onError | function(error) | | You can specify a function or class that will be triggered when endpoint fails. If it's a class it should expose a `process` method. When using native fetch(), the full Response Object is sent as a first argument of the function. In case of Axios, AxiosError object is sent. |
-| logger | object | | You can additionally specify logger object with your custom logger to automatically log the errors to the console. It should contain at least `error` and `warn` functions. `console.log` is used by default. |
-| method | string | get | Default request method e.g. GET, POST, DELETE, PUT etc. |
-| url | string | | URL path e.g. /user-details/get |
-| urlPathParams | object | {} | An object representing URL path parameters. These parameters are used to dynamically replace placeholders in the URL path. For example, if your URL contains a placeholder like `/users/:userId`, you can provide an object with the `userId` key to replace that placeholder with an actual value. The keys in the `urlPathParams` object should match the placeholders in the URL. This allows for dynamic URL construction based on runtime values. |
-| retry | object | | The object with retry settings available below. |
-| retry.retries | number | 0 | The number of times to retry the request in case of failure. If set to `0` (default), no retries will be attempted. |
-| retry.delay | number | 1000 | The initial delay (in milliseconds) between retry attempts. |
-| retry.backoff | number | 1.5 | The backoff factor to apply to the delay between retries. For example, if the delay is 100ms and the backoff is 1.5, the next delay will be 150ms, then 225ms, and so on. |
-| retry.maxDelay | number | 30000 | The maximum delay (in milliseconds) between retry attempts. |
-| retry.retryOn | array | [408, 409, 425, 429, 500, 502, 503, 504] | An array of HTTP status codes on which to retry the request. Default values include: 408 (Request Timeout), 409 (Conflict), 425 (Too Early), 429 (Too Many Requests), 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout). |
-| retry.shouldRetry | async function | | A custom asynchronous function to determine whether to retry the request. It receives two arguments: `error` (the error object) and `attempts` (the number of attempts made so far). |
+## Comparison with another libraries
+
+| Feature | axios-multi-api | ofetch() | Wretch() | Axios | SWR | React Query | Native fetch() |
+| --------------------------------------- | --------------- | ------------ | ------------ | ------------ | ------------ | ------------ | -------------- |
+| **Unified API Client** | ✅ | -- | -- | -- | -- | -- | -- |
+| **Customizable Error Handling** | ✅ | -- | ✅ | ✅ | ✅ | ✅ | -- |
+| **Retries with exponential backoff** | ✅ | -- | -- | -- | ✅ | ✅ | -- |
+| **Easy Timeouts** | ✅ | ✅ | ✅ | ✅ | -- | -- | -- |
+| **Easy Cancellation** | ✅ | -- | -- | -- | ✅ | ✅ | -- |
+| **Default Responses** | ✅ | -- | -- | -- | -- | -- | -- |
+| **Global Configuration** | ✅ | -- | ✅ | ✅ | ✅ | ✅ | -- |
+| **TypeScript Support** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| **Interceptors** | ✅ | ✅ | ✅ | ✅ | -- | -- | -- |
+| **Request and Response Transformation** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -- |
+| **Integration with Libraries** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -- |
+| **Request Queuing** | ✅ | -- | -- | -- | -- | -- | -- |
+| **Multiple Fetching Strategies** | ✅ | -- | -- | -- | -- | -- | -- |
+| **Dynamic URLs** | ✅ | -- | ✅ | -- | -- | -- | -- |
+| **Automatic Retry on Failure** | ✅ | ✅ | -- | ✅ | ✅ | ✅ | -- |
+| **Server-Side Rendering (SSR) Support** | ✅ | ✅ | -- | -- | ✅ | ✅ | -- |
+| **Pagination Handling** | -- | -- | -- | -- | ✅ | ✅ | -- |
+| **Caching** | -- | -- | -- | -- | ✅ | ✅ | -- |
+| **Optimistic Updates** | -- | -- | -- | -- | ✅ | ✅ | -- |
+| **Data Synchronization** | -- | -- | -- | -- | ✅ | ✅ | -- |
+| **Local State Management** | -- | -- | -- | -- | ✅ | ✅ | -- |
+| **Minimal Installation Size** | 🟢 (2.83 KB) | 🟡 (6.51 KB) | 🟢 (2.16 KB) | 🔴 (13.9 KB) | 🟡 (4.57 KB) | 🔴 (13.3 KB) | 🟢 (0 KB) |
+| **Built-in AbortController Support** | ✅ | -- | -- | -- | ✅ | ✅ | -- |
+
+Please mind that this table is for informational purposes only. All of these solutions differ. For example `swr` and `react-query` are more focused on React, re-rendering, query caching and keeping data in sync, while fetch wrappers like `axios-multi-api` or `ofetch` aim to extend functionalities of native `fetch` so to reduce complexity of having to maintain various wrappers.
## ✔️ Full TypeScript support
@@ -378,6 +589,35 @@ try {
}
```
+### Multiple APIs from different API sources
+
+```typescript
+import { createApiFetcher } from 'axios-multi-api';
+
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api/v1',
+ endpoints: {
+ sendMessage: {
+ method: 'post',
+ url: '/send-message/:postId',
+ },
+ getMessage: {
+ url: '/get-message/',
+ // Change baseURL to external for this endpoint onyl
+ baseURL: 'https://externalprovider.com/api/v2',
+ },
+ },
+});
+
+async function sendAndGetMessage() {
+ await api.sendMessage({ message: 'Text' }, { postId: 1 });
+
+ const { data } = await api.getMessage({ postId: 1 });
+}
+
+sendAndGetMessage();
+```
+
### Retry Mechanism
Here’s an example of configuring and using the `createApiFetcher()` with the retry mechanism:
@@ -505,6 +745,38 @@ async function sendMessage() {
sendMessage();
```
+### Per-request Error handling - softFail strategy (recommended)
+
+```typescript
+import { createApiFetcher } from 'axios-multi-api';
+
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api',
+ strategy: 'softFail',
+ endpoints: {
+ sendMessage: {
+ method: 'post',
+ url: '/send-message/:postId',
+ },
+ },
+});
+
+async function sendMessage() {
+ const { data, error } = await api.sendMessage(
+ { message: 'Text' },
+ { postId: 1 },
+ );
+
+ if (error) {
+ console.error('Request Error', error);
+ } else {
+ console.log('Message sent successfully');
+ }
+}
+
+sendMessage();
+```
+
### Per-request Error handling - defaultResponse strategy
```typescript
@@ -647,6 +919,75 @@ const { data } = await fetchf('/api/user-details', {
});
```
+### Integration with Vue
+
+```typescript
+// src/api.ts
+import { createApiFetcher } from 'axios-multi-api';
+
+const api = createApiFetcher({
+ apiUrl: 'https://example.com/api',
+ strategy: 'softFail',
+ endpoints: {
+ getProfile: { url: '/profile/:id' },
+ },
+});
+
+export default api;
+```
+
+```typescript
+// src/composables/useProfile.ts
+import { ref, onMounted } from 'vue';
+import api from '../api';
+
+export function useProfile(id: number) {
+ const profile = ref(null);
+ const isLoading = ref(true);
+ const isError = ref(null);
+
+ const fetchProfile = async () => {
+ const { data, error } = await api.getProfile({ id });
+
+ if (error) isError.value = error;
+ else if (data) profile.value = data;
+
+ isLoading.value = false;
+ };
+
+ onMounted(fetchProfile);
+
+ return { profile, isLoading, isError };
+}
+```
+
+```html
+
+
+
+
Profile
+
Loading...
+
Error: {{ isError.message }}
+
+
Name: {{ profile.name }}
+
Email: {{ profile.email }}
+
+
+
+
+
+```
+
## ✔️ Support and collaboration
If you have any idea for an improvement, please file an issue. Feel free to make a PR if you are willing to collaborate on the project. Thank you :)
diff --git a/dist/browser/index.global.js b/dist/browser/index.global.js
index 58df972..9b1dd86 100644
--- a/dist/browser/index.global.js
+++ b/dist/browser/index.global.js
@@ -1,2 +1,2 @@
-(()=>{var g=class{logger;requestErrorService;constructor(e,t){this.logger=e,this.requestErrorService=t}process(e){var s;(s=this.logger)!=null&&s.warn&&this.logger.warn("API ERROR",e);let t=e;typeof e=="string"&&(t=new Error(e)),this.requestErrorService&&(typeof this.requestErrorService.process<"u"?this.requestErrorService.process(t):typeof this.requestErrorService=="function"&&this.requestErrorService(t))}};var q=class u extends Error{response;request;constructor(e,t,s){super(e),this.name="RequestError",this.message=e,this.request=t,this.response=s,Error.captureStackTrace(this,u)}};async function C(u,e){if(!e)return u;let t=Array.isArray(e)?e:[e],s={...u};for(let r of t)s=await r(s);return s}async function E(u,e){if(!e)return u;let t=Array.isArray(e)?e:[e],s=u;for(let r of t)s=await r(s);return s}var R=class{requestInstance;baseURL="";timeout=3e4;cancellable=!1;rejectCancelled=!1;strategy="reject";method="get";flattenResponse=!1;defaultResponse=null;fetcher;logger;onError;requestsQueue;retry={retries:0,delay:1e3,maxDelay:3e4,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504],shouldRetry:async()=>!0};config;constructor({fetcher:e=null,timeout:t=null,rejectCancelled:s=!1,strategy:r=null,flattenResponse:o=null,defaultResponse:a={},logger:n=null,onError:i=null,...l}){this.fetcher=e,this.timeout=t??this.timeout,this.strategy=r??this.strategy,this.cancellable=l.cancellable||this.cancellable,this.rejectCancelled=s||this.rejectCancelled,this.flattenResponse=o??this.flattenResponse,this.defaultResponse=a,this.logger=n||(globalThis?globalThis.console:null)||null,this.onError=i,this.requestsQueue=new WeakMap,this.baseURL=l.baseURL||l.apiUrl||"",this.method=l.method||this.method,this.config=l,this.retry={...this.retry,...l.retry||{}},this.requestInstance=this.isCustomFetcher()?e.create({...l,baseURL:this.baseURL,timeout:this.timeout}):null}getInstance(){return this.requestInstance}replaceUrlPathParams(e,t){return t?e.replace(/:[a-zA-Z]+/gi,s=>{let r=s.substring(1);return String(t[r]?t[r]:s)}):e}appendQueryParams(e,t){if(!t)return e;let s=Object.entries(t).flatMap(([r,o])=>Array.isArray(o)?o.map(a=>`${encodeURIComponent(r)}[]=${encodeURIComponent(a)}`):`${encodeURIComponent(r)}=${encodeURIComponent(String(o))}`).join("&");return e.includes("?")?`${e}&${s}`:s?`${e}?${s}`:e}isJSONSerializable(e){if(e==null)return!1;let t=typeof e;if(t==="string"||t==="number"||t==="boolean")return!0;if(t!=="object")return!1;if(Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;let s=Object.getPrototypeOf(e);return s===Object.prototype||s===null||typeof e.toJSON=="function"}buildConfig(e,t,s){let r=s.method||this.method,o=r.toLowerCase(),a=o==="get"||o==="head",n=this.replaceUrlPathParams(e,s.urlPathParams||this.config.urlPathParams),i=s.body||s.data||this.config.body||this.config.data;if(this.isCustomFetcher())return{...s,url:n,method:o,...a?{params:t}:{},...!a&&t&&i?{params:t}:{},...!a&&t&&!i?{data:t}:{},...!a&&i?{data:i}:{}};let l=i||t;delete s.data;let d=!a&&t&&!s.body||!t?n:this.appendQueryParams(n,t),m=d.includes("://")?"":typeof s.baseURL<"u"?s.baseURL:this.baseURL;return{...s,url:m+d,method:r.toUpperCase(),headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8",...s.headers||this.config.headers||{}},...a?{}:{body:this.isJSONSerializable(l)?typeof l=="string"?l:JSON.stringify(l):l}}}processError(e,t){if(this.isRequestCancelled(e))return;t.onError&&typeof t.onError=="function"&&t.onError(e),new g(this.logger,this.onError).process(e)}async outputErrorResponse(e,t){let s=this.isRequestCancelled(e),r=t.strategy||this.strategy,o=typeof t.rejectCancelled<"u"?t.rejectCancelled:this.rejectCancelled,a=typeof t.defaultResponse<"u"?t.defaultResponse:this.defaultResponse;return s&&!o?a:r==="silent"?(await new Promise(()=>null),a):r==="reject"?Promise.reject(e):a}isRequestCancelled(e){return e.name==="AbortError"||e.name==="CanceledError"}isCustomFetcher(){return this.fetcher!==null}addCancellationToken(e){if(!this.cancellable&&!e.cancellable)return{};if(typeof e.cancellable<"u"&&!e.cancellable)return{};if(typeof AbortController>"u")return console.error("AbortController is unavailable."),{};let t=this.requestsQueue.get(e);t&&t.abort();let s=new AbortController;if(!this.isCustomFetcher()){let r=setTimeout(()=>{let o=new Error(`[TimeoutError]: The ${e.url} request was aborted due to timeout`);throw o.name="TimeoutError",o.code=23,s.abort(o),clearTimeout(r),o},e.timeout||this.timeout)}return this.requestsQueue.set(e,s),{signal:s.signal}}async request(e,t=null,s=null){var P,w,A;let r=null,o=s||{},a=this.buildConfig(e,t,o),n={...this.addCancellationToken(a),...a},{retries:i,delay:l,backoff:d,retryOn:h,shouldRetry:m,maxDelay:b}={...this.retry,...(n==null?void 0:n.retry)||{}},f=0,y=l;for(;f<=i;)try{if(n=await C(n,n.onRequest),n=await C(n,this.config.onRequest),this.isCustomFetcher())r=await this.requestInstance.request(n);else if(r=await globalThis.fetch(n.url,n),r.config=n,r.ok){let c=String(((P=r==null?void 0:r.headers)==null?void 0:P.get("Content-Type"))||""),p=null;if(!c)try{p=await r.json()}catch{}p||(c&&c.includes("application/json")?p=await r.json():typeof r.text<"u"?p=await r.text():typeof r.blob<"u"?p=await r.blob():p=r.body||r.data||null),r.data=p}else throw r.data=null,new q(`fetchf() Request Failed! Status: ${r.status||null}`,n,r);return r=await E(r,n.onResponse),r=await E(r,this.config.onResponse),this.processResponseData(r,n)}catch(c){if(f===i||!await m(c,f)||!(h!=null&&h.includes((r==null?void 0:r.status)||((w=c==null?void 0:c.response)==null?void 0:w.status)||(c==null?void 0:c.status))))return this.processError(c,n),this.outputErrorResponse(c,n);(A=this.logger)!=null&&A.warn&&this.logger.warn(`Attempt ${f+1} failed. Retrying in ${y}ms...`),await this.delay(y),y*=d,y=Math.min(y,b),f++}return this.processResponseData(r,n)}async delay(e){return new Promise(t=>setTimeout(()=>t(!0),e))}processResponseData(e,t){var o;let s=typeof t.defaultResponse<"u"?t.defaultResponse:this.defaultResponse;return e?(t.flattenResponse||this.flattenResponse)&&typeof e.data<"u"?typeof e.data=="object"&&typeof e.data.data<"u"&&Object.keys(e.data).length===1?e.data.data:e.data:typeof e=="object"&&e.constructor===Object&&Object.keys(e).length===0?s:this.isCustomFetcher()?e:{...e,headers:Array.from(((o=e==null?void 0:e.headers)==null?void 0:o.entries())||{}).reduce((a,[n,i])=>(a[n]=i,a),{}),config:t}:s}};function Q(u){let e=u.endpoints,t=new R(u);function s(){return t.getInstance()}function r(i){return console.error(`${i} endpoint must be added to 'endpoints'.`),Promise.resolve(null)}async function o(i,l={},d={},h={}){let b={...e[i]};return await t.request(b.url,l,{...b,...h,urlPathParams:d})}function a(i){return i in n?n[i]:e[i]?n.request.bind(null,i):r.bind(null,i)}let n={config:u,endpoints:e,requestHandler:t,getInstance:s,request:o};return new Proxy(n,{get:(i,l)=>a(l)})}async function D(u,e={}){return new R(e).request(u,e.body||e.data||e.params,e)}})();
+(()=>{async function C(u,e){if(!e)return u;let s=Array.isArray(e)?e:[e],t={...u};for(let n of s)t=await n(t);return t}async function P(u,e){if(!e)return u;let s=Array.isArray(e)?e:[e],t=u;for(let n of s)t=await n(t);return t}var b=class extends Error{response;request;config;status;statusText;constructor(e,s,t){super(e),this.name="ResponseError",this.message=e,this.status=t.status,this.statusText=t.statusText,this.request=s,this.config=s,this.response=t}};var R=class{requestInstance;baseURL="";timeout=3e4;cancellable=!1;rejectCancelled=!1;strategy="reject";method="get";flattenResponse=!1;defaultResponse=null;fetcher;logger;onError;requestsQueue;retry={retries:0,delay:1e3,maxDelay:3e4,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504],shouldRetry:async()=>!0};config;constructor({fetcher:e=null,timeout:s=null,rejectCancelled:t=!1,strategy:n=null,flattenResponse:o=null,defaultResponse:i={},logger:r=null,onError:a=null,...l}){this.fetcher=e,this.timeout=s??this.timeout,this.strategy=n||this.strategy,this.cancellable=l.cancellable||this.cancellable,this.rejectCancelled=t||this.rejectCancelled,this.flattenResponse=o||this.flattenResponse,this.defaultResponse=i,this.logger=r||(globalThis?globalThis.console:null)||null,this.onError=a,this.requestsQueue=new WeakMap,this.baseURL=l.baseURL||l.apiUrl||"",this.method=l.method||this.method,this.config=l,this.retry={...this.retry,...l.retry||{}},this.requestInstance=this.isCustomFetcher()?e.create({...l,baseURL:this.baseURL,timeout:this.timeout}):null}getInstance(){return this.requestInstance}replaceUrlPathParams(e,s){return s?e.replace(/:[a-zA-Z]+/gi,t=>{let n=t.substring(1);return String(s[n]?s[n]:t)}):e}appendQueryParams(e,s){if(!s)return e;let t=Object.entries(s).flatMap(([n,o])=>Array.isArray(o)?o.map(i=>`${encodeURIComponent(n)}[]=${encodeURIComponent(i)}`):`${encodeURIComponent(n)}=${encodeURIComponent(String(o))}`).join("&");return e.includes("?")?`${e}&${t}`:t?`${e}?${t}`:e}isJSONSerializable(e){if(e==null)return!1;let s=typeof e;if(s==="string"||s==="number"||s==="boolean")return!0;if(s!=="object")return!1;if(Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||typeof e.toJSON=="function"}buildConfig(e,s,t){let n=t.method||this.method,o=n.toLowerCase(),i=o==="get"||o==="head",r=this.replaceUrlPathParams(e,t.urlPathParams||this.config.urlPathParams),a=t.body||t.data||this.config.body||this.config.data;if(this.isCustomFetcher())return{...t,url:r,method:o,...i?{params:s}:{},...!i&&s&&a?{params:s}:{},...!i&&s&&!a?{data:s}:{},...!i&&a?{data:a}:{}};let l=a||s,y=t.withCredentials||this.config.withCredentials?"include":t.credentials;delete t.data,delete t.withCredentials;let p=!i&&s&&!t.body||!s?r:this.appendQueryParams(r,s),h=p.includes("://")?"":typeof t.baseURL<"u"?t.baseURL:this.baseURL;return{...t,credentials:y,url:h+p,method:n.toUpperCase(),headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8",...t.headers||this.config.headers||{}},...i?{}:{body:this.isJSONSerializable(l)?typeof l=="string"?l:JSON.stringify(l):l}}}processError(e,s){var t;this.isRequestCancelled(e)||((t=this.logger)!=null&&t.warn&&this.logger.warn("API ERROR",e),s.onError&&typeof s.onError=="function"&&s.onError(e),this.onError&&typeof this.onError=="function"&&this.onError(e))}async outputErrorResponse(e,s){let t=this.isRequestCancelled(e),n=s.strategy||this.strategy,o=typeof s.rejectCancelled<"u"?s.rejectCancelled:this.rejectCancelled,i=typeof s.defaultResponse<"u"?s.defaultResponse:this.defaultResponse;return n==="softFail"?this.outputResponse(e.response,s,e):t&&!o?i:n==="silent"?(await new Promise(()=>null),i):n==="reject"?Promise.reject(e):i}isRequestCancelled(e){return e.name==="AbortError"||e.name==="CanceledError"}isCustomFetcher(){return this.fetcher!==null}addCancellationToken(e){if(!this.cancellable&&!e.cancellable)return{};if(typeof e.cancellable<"u"&&!e.cancellable)return{};if(typeof AbortController>"u")return console.error("AbortController is unavailable."),{};let s=this.requestsQueue.get(e);s&&s.abort();let t=new AbortController;if(!this.isCustomFetcher()&&this.timeout>0){let n=setTimeout(()=>{let o=new Error(`[TimeoutError]: The ${e.url} request was aborted due to timeout`);throw o.name="TimeoutError",o.code=23,t.abort(o),clearTimeout(n),o},e.timeout||this.timeout)}return this.requestsQueue.set(e,t),{signal:t.signal}}async request(e,s=null,t=null){var q,w,F;let n=null,o=t||{},i=this.buildConfig(e,s,o),r={...this.addCancellationToken(i),...i},{retries:a,delay:l,backoff:y,retryOn:p,shouldRetry:g,maxDelay:h}={...this.retry,...(r==null?void 0:r.retry)||{}},f=0,m=l;for(;f<=a;)try{if(r=await C(r,r.onRequest),r=await C(r,this.config.onRequest),this.isCustomFetcher())n=await this.requestInstance.request(r);else{n=await globalThis.fetch(r.url,r);let c=String(((q=n==null?void 0:n.headers)==null?void 0:q.get("Content-Type"))||""),d;if(!c)try{d=await n.json()}catch{}if(typeof d>"u"&&(c&&c.includes("application/json")?d=await n.json():typeof n.text<"u"?d=await n.text():typeof n.blob<"u"?d=await n.blob():d=n.body||n.data||null),n.config=r,n.data=d,!n.ok)throw new b(`${r.url} failed! Status: ${n.status||null}`,r,n)}return n=await P(n,r.onResponse),n=await P(n,this.config.onResponse),this.outputResponse(n,r)}catch(c){if(f===a||!await g(c,f)||!(p!=null&&p.includes(((w=c==null?void 0:c.response)==null?void 0:w.status)||(c==null?void 0:c.status))))return this.processError(c,r),this.outputErrorResponse(c,r);(F=this.logger)!=null&&F.warn&&this.logger.warn(`Attempt ${f+1} failed. Retrying in ${m}ms...`),await this.delay(m),m*=y,m=Math.min(m,h),f++}return this.outputResponse(n,r)}async delay(e){return new Promise(s=>setTimeout(()=>s(!0),e))}processHeaders(e){if(!e.headers)return{};let s={};if(e.headers instanceof Headers)for(let[t,n]of e.headers.entries())s[t]=n;else s={...e.headers};return s}outputResponse(e,s,t=null){let n=typeof s.defaultResponse<"u"?s.defaultResponse:this.defaultResponse;return e?(s.flattenResponse||this.flattenResponse)&&typeof e.data<"u"?e.data!==null&&typeof e.data=="object"&&typeof e.data.data<"u"&&Object.keys(e.data).length===1?e.data.data:e.data:e!==null&&typeof e=="object"&&e.constructor===Object&&Object.keys(e).length===0?n:this.isCustomFetcher()?e:(t!==null&&(t==null||delete t.response,t==null||delete t.request,t==null||delete t.config),{...e,error:t,headers:this.processHeaders(e),config:s}):n}};function T(u){let e=u.endpoints,s=new R(u);function t(){return s.getInstance()}function n(a){return console.error(`${a} endpoint must be added to 'endpoints'.`),Promise.resolve(null)}async function o(a,l={},y={},p={}){let h={...e[a]};return await s.request(h.url,l,{...h,...p,urlPathParams:y})}function i(a){return a in r?r[a]:e[a]?r.request.bind(null,a):n.bind(null,a)}let r={config:u,endpoints:e,requestHandler:s,getInstance:t,request:o};return new Proxy(r,{get:(a,l)=>i(l)})}async function $(u,e={}){return new R(e).request(u,e.body||e.data||e.params,e)}})();
//# sourceMappingURL=index.global.js.map
\ No newline at end of file
diff --git a/dist/browser/index.global.js.map b/dist/browser/index.global.js.map
index 0d2fc2e..a9a77a6 100644
--- a/dist/browser/index.global.js.map
+++ b/dist/browser/index.global.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../src/request-error-handler.ts","../src/request-error.ts","../src/interceptor-manager.ts","../src/request-handler.ts","../src/api-handler.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nexport class RequestErrorHandler {\n /**\n * Logger Class\n *\n * @type {*}\n * @memberof RequestErrorHandler\n */\n protected logger: any;\n\n /**\n * Error Service Class\n *\n * @type {*}\n * @memberof RequestErrorHandler\n */\n public requestErrorService: any;\n\n public constructor(logger: any, requestErrorService: any) {\n this.logger = logger;\n this.requestErrorService = requestErrorService;\n }\n\n /**\n * Process and Error\n *\n * @param {*} error Error instance or message\n * @throws Request error context\n * @returns {void}\n */\n public process(error: string | Error): void {\n if (this.logger?.warn) {\n this.logger.warn('API ERROR', error);\n }\n\n let errorContext = error;\n\n if (typeof error === 'string') {\n errorContext = new Error(error);\n }\n\n if (this.requestErrorService) {\n if (typeof this.requestErrorService.process !== 'undefined') {\n this.requestErrorService.process(errorContext);\n } else if (typeof this.requestErrorService === 'function') {\n this.requestErrorService(errorContext);\n }\n }\n }\n}\n","import type { RequestConfig } from './types';\n\nexport class RequestError extends Error {\n response: Response;\n request: RequestConfig;\n\n constructor(message: string, requestInfo: RequestConfig, response: Response) {\n super(message);\n\n this.name = 'RequestError';\n this.message = message;\n this.request = requestInfo;\n this.response = response;\n\n // Clean stack trace\n Error.captureStackTrace(this, RequestError);\n }\n}\n","import type {\n BaseRequestHandlerConfig,\n FetchResponse,\n RequestResponse,\n} from './types';\nimport type {\n RequestInterceptor,\n ResponseInterceptor,\n} from './types/interceptor-manager';\n\n/**\n * Applies a series of request interceptors to the provided configuration.\n * @param {BaseRequestHandlerConfig} config - The initial request configuration.\n * @param {RequestInterceptor | RequestInterceptor[]} interceptors - The request interceptor function(s) to apply.\n * @returns {Promise} - The modified request configuration.\n */\nexport async function interceptRequest(\n config: BaseRequestHandlerConfig,\n interceptors: RequestInterceptor | RequestInterceptor[],\n): Promise {\n if (!interceptors) {\n return config;\n }\n\n const interceptorList = Array.isArray(interceptors)\n ? interceptors\n : [interceptors];\n\n let interceptedConfig = { ...config };\n\n for (const interceptor of interceptorList) {\n interceptedConfig = await interceptor(interceptedConfig);\n }\n\n return interceptedConfig;\n}\n\n/**\n * Applies a series of response interceptors to the provided response.\n * @param {FetchResponse} response - The initial response object.\n * @param {ResponseInterceptor | ResponseInterceptor[]} interceptors - The response interceptor function(s) to apply.\n * @returns {Promise>} - The modified response object.\n */\nexport async function interceptResponse(\n response: FetchResponse,\n interceptors: ResponseInterceptor | ResponseInterceptor[],\n): Promise> {\n if (!interceptors) {\n return response;\n }\n\n const interceptorList = Array.isArray(interceptors)\n ? interceptors\n : [interceptors];\n\n let interceptedResponse = response;\n\n for (const interceptor of interceptorList) {\n interceptedResponse = await interceptor(interceptedResponse);\n }\n\n return interceptedResponse;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RequestErrorHandler } from './request-error-handler';\nimport type {\n ErrorHandlingStrategy,\n RequestHandlerConfig,\n RequestConfig,\n RequestError as RequestErrorResponse,\n FetcherInstance,\n Method,\n RequestConfigHeaders,\n RetryOptions,\n FetchResponse,\n ExtendedResponse,\n} from './types/request-handler';\nimport type {\n APIResponse,\n QueryParams,\n QueryParamsOrBody,\n UrlPathParams,\n} from './types/api-handler';\nimport { RequestError } from './request-error';\nimport { interceptRequest, interceptResponse } from './interceptor-manager';\n\n/**\n * Generic Request Handler\n * It creates an Request Fetcher instance and handles requests within that instance\n * It handles errors depending on a chosen error handling strategy\n */\nexport class RequestHandler {\n /**\n * @var requestInstance Provider's instance\n */\n public requestInstance: FetcherInstance;\n\n /**\n * @var baseURL Base API url\n */\n public baseURL: string = '';\n\n /**\n * @var timeout Request timeout\n */\n public timeout: number = 30000;\n\n /**\n * @var cancellable Response cancellation\n */\n public cancellable: boolean = false;\n\n /**\n * @var rejectCancelled Whether to reject cancelled requests or not\n */\n public rejectCancelled: boolean = false;\n\n /**\n * @var strategy Request timeout\n */\n public strategy: ErrorHandlingStrategy = 'reject';\n\n /**\n * @var method Request method\n */\n public method: Method | string = 'get';\n\n /**\n * @var flattenResponse Response flattening\n */\n public flattenResponse: boolean = false;\n\n /**\n * @var defaultResponse Response flattening\n */\n public defaultResponse: any = null;\n\n /**\n * @var fetcher Request Fetcher instance\n */\n protected fetcher: FetcherInstance;\n\n /**\n * @var logger Logger\n */\n protected logger: any;\n\n /**\n * @var requestErrorService HTTP error service\n */\n protected onError: any;\n\n /**\n * @var requestsQueue Queue of requests\n */\n protected requestsQueue: WeakMap