UNPKG

11.7 kBMarkdownView Raw
1es-fetcher: Simplify API integration and content fetching in front-end applications.<br/>
2[![NPM Version](https://img.shields.io/npm/v/es-fetcher.svg?branch=main)](https://www.npmjs.com/package/es-fetcher)
3[![Publish Size](https://badgen.net/packagephobia/publish/es-fetcher)](https://packagephobia.now.sh/result?p=es-fetcher)
4[![Downloads](https://img.shields.io/npm/dt/es-fetcher)](https://www.npmjs.com/package/es-fetcher)
5[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/SheikhAminul/es-fetcher/blob/main/LICENSE)
6================
7
8es-fetcher is a versatile and lightweight JavaScript library that simplifies API integration and data fetching in front-end applications, making it faster and more efficient than ever before. With a set of utility functions and configuration options, this package streamlines your API requests, caching, and error handling.
9
10## Table of Contents
11* [Features](#features)
12* [Install](#install)
13* [Usage](#usage)
14* [API Reference](#API_Reference)
15* [Contributing](#contributing)
16* [License](#license)
17* [Author](#author)
18
19## Features
20* **Effortless API Integration:** With es-fetcher, you can easily integrate external APIs into your front-end application, saving you time and effort.
21* **React Hook:** Simplify data fetching and state management in your React application with the **`useFetch`** hook.
22* **Flexible Configuration:** Configure the fetcher to match your application's specific requirements, including base URLs, access tokens, authentication methods, headers, and more.
23* **Automatic Data Parsing:** es-fetcher automatically parses response data based on the content type, supporting JSON, XML, Blob, and text.
24* **Memory Caching:** Improve performance and reduce redundant API calls by caching responses in memory with the ability to easily clear the entire memory cache or delete specific cached data by URL or URL patterns.
25* **Community-Driven:** es-fetcher is open-source, and we welcome contributions from the community. Join us in making it even better!
26
27## Install
28```plaintext
29npm i es-fetcher
30```
31
32
33## Usage
34
35### Fetch (API calls) with authentication
36A minimal example of fetching with authentication.
37
38```typescript
39import { fetch, configureFetcher } from 'es-fetcher'
40
41// Configure API access token, base URL, authentication method, and more
42configureFetcher({
43 baseUrl: 'https://api.example.com/dev/',
44 accessToken: 'your-access-token',
45 authMethod: 'bearer',
46 headers: { 'Content-Type': 'application/json' }
47})
48
49// Fetch in GET method example
50const users = await fetch('/users')
51
52// Fetch from cache instead of making API call (GET only) example
53const countries = await fetch('/utils/countries', { cache: 'memory-cache' })
54
55// Basic POST example
56const result = await fetch('/customer/add', {
57 method: 'POST',
58 body: JSON.stringify({
59 name: 'John Doe',
60 age: 30
61 })
62})
63```
64
65### React integration (useFetch hook)
66
67Data fetching and state management in your React application with the **`useFetch`** hook.
68```typescript
69import { useFetch } from 'es-fetcher'
70
71function UserList() {
72 const { fetchedData, loading, error } = useFetch('/users')
73
74 if (loading) return <p>Loading...</p>
75
76 if (error) return <p>Error!</p>
77
78 return (
79 <ul>
80 {fetchedData.map(user => (
81 <li key={user.id}>{user.name}</li>
82 ))}
83 </ul>
84 )
85}
86```
87
88Example of using memory-cache for GET requests. If a cache is not available for the URL, it will fetch and cache the data. Upon subsequent requests or renders, it will return the cached data.
89```typescript
90import { useFetch } from 'es-fetcher'
91
92function UserList() {
93 const { fetchedData, loading, error } = useFetch('/users', { cache: 'memory-cache' })
94
95 if (loading) return <p>Loading...</p>
96
97 if (error) return <p>Error!</p>
98
99 return (
100 <ul>
101 {fetchedData.map(user => (
102 <li key={user.id}>{user.name}</li>
103 ))}
104 </ul>
105 )
106}
107```
108
109## API Reference
110
111### **Core:**
112
113### **`configureFetcher(configuration: FetchConfiguration)`**
114Use the `configureFetcher` function to configure the global fetch settings. This function allows you to set various options that will apply to all subsequent fetch requests for the supplied base URL.
115
116Parameters:
117* `configuration` (`FetchConfiguration`): Global fetch settings, as defined in the `FetchConfiguration` interface.
118
119Example:
120```typescript
121import { configureFetcher } from 'es-fetcher'
122
123configureFetcher({
124 baseUrl: 'https://api.example.com',
125 accessToken: 'your-access-token',
126 cache: 'no-store',
127 credentials: 'include',
128 headers: {
129 'Accept': 'application/json'
130 },
131 mode: 'cors'
132})
133```
134
135### **`useFetch(url: string, options?: FetchOptions)`**
136`useFetch` is a custom React Hook provided by es-fetcher for data fetching in functional components. It simplifies the process of making fetch requests and managing the state of your component.
137
138Parameters:
139* `url` (string): The URL to fetch data from. It can be either an absolute or relative URL.
140* `options` (`FetchOptions`, optional): Custom options for the fetch request, as defined in the `FetchOptions` interface.
141
142Return Values:
143* `loading` (boolean): A boolean value indicating whether the request is in progress.
144* `fetchedData` (any): The fetched data if the request is successful.
145* `error` (string): An error message if the request fails.
146
147Example:
148```typescript
149const { loading, fetchedData, error } = useFetch('/api/users', { cache: 'memory-cache' })
150```
151
152### **`fetch(url: string, options?: FetchOptions)`**
153The `fetch` function makes fetch request using the provided URL and options and returns the fetched data. This function handles various HTTP methods, caching, and other configurations.
154
155Parameters:
156* `url` (string): The URL to make the API request to.
157* `options` (`FetchOptions`, optional): Optional request options that override the global configuration for this specific request.
158
159Return Values:
160* `fetchedData` (any): The fetched data if the request is successful.
161
162Example:
163```typescript
164const countries = await fetch('/utils/countries', {
165 cache: 'memory-cache',
166 headers: {
167 'Accept': 'application/json'
168 }
169})
170```
171
172### **Caching:**
173
174### **`clearMemoryCache()`**
175The `clearMemoryCache` function clears the entire memory cache.
176
177### **`deleteMemoryCache(urlPattern: string)`**
178The `deleteMemoryCache` function is used to clear cached responses from the memory cache for a specific URL pattern. It allows you to selectively remove cached data for a single URL or a specific URL pattern.
179
180Parameters:
181* `urlPattern` (string): The URL pattern for which you want to clear cached data. This pattern can include wildcards (*) to match multiple URLs.
182
183Example:
184```typescript
185import { deleteMemoryCache } from 'es-fetcher'
186
187// Delete cached data for specific URLs
188deleteMemoryCache('https://example.com/user/me')
189deleteMemoryCache('/user/me')
190
191// Delete cached data for all URLs that match a pattern
192deleteMemoryCache('https://example.com/*') // Deletes for all URLs in this site
193deleteMemoryCache('/user/*')
194```
195
196### **`deleteMemoryCaches(urlPatterns: string[])`**
197The `deleteMemoryCaches` function functions similarly to `deleteMemoryCache`, but it accepts multiple URL patterns in the form of an array.
198
199Parameters:
200* `urlPatterns` (string[]): The URL patterns for which you want to clear cached data.
201
202Example:
203```typescript
204import { deleteMemoryCaches } from 'es-fetcher'
205
206deleteMemoryCaches([
207 '/user/*',
208 '/me/follower/*',
209 'https://api.example.com/user/me'
210])
211```
212
213### **Interfaces:**
214
215### **`FetchConfiguration`**
216The `FetchConfiguration` interface defines the global fetch settings.
217- `baseUrl` (string, optional): The base URL for API requests. Defaults to `location.origin`.
218
219- `accessToken` (string, optional): An access token to include in the request headers for authentication.
220
221- `authMethod` (string, optional): The authentication method to use. Currently supports only 'bearer' for Bearer Token authentication.
222
223- `cache` (string, optional): The caching strategy to use. Options include:
224 - `'default'` (default): Use the browser's default caching behavior.
225 - `'force-cache'`: Always use the cached response.
226 - `'no-cache'`: Bypass the cache and make a request to the server.
227 - `'no-store'`: Bypass the cache completely.
228 - `'only-if-cached'`: Use a cached response if available; otherwise, make a request.
229 - `'reload'`: Bypass the cache and request the server for a new response.
230 - `'memory-cache'`: Enable in-memory caching for GET requests.
231
232- `credentials` (string, optional): The credentials mode for the request. Options include:
233 - `'include'`: Include credentials (e.g., cookies) in the request.
234 - `'omit'`: Omit credentials from the request.
235 - `'same-origin'` (default): Include credentials only if the request is on the same origin.
236
237- `headers` (array, object, or Headers, optional): Custom headers to include in the request.
238
239- `mode` (string, optional): The mode of the request. Options include:
240 - `'cors'` (default): Make a cross-origin request with CORS headers.
241 - `'navigate'`: Make a navigation request (e.g., for page reload).
242 - `'no-cors'`: Make a no-cors request, limited to same-origin requests.
243 - `'same-origin'`: Make a same-origin request.
244
245### **`FetchOptions`**
246The `FetchOptions` interface defines custom settings that you can apply to fetch call.
247- `body` (BodyInit | null, optional): The request body data. It can be a string, FormData, Blob, ArrayBufferView, or null.
248
249- `cache` (string, optional): The caching strategy for the request. Options are the same as in `FetchConfiguration.cache`.
250
251- `credentials` (string, optional): The credentials mode for the request. Options are the same as in `FetchConfiguration.credentials`.
252
253- `headers` (array, object, or Headers, optional): Custom headers to include in the request. These headers are merged with the global configuration headers.
254
255- `integrity` (string, optional): Subresource integrity value to ensure the fetched resource has not been tampered with.
256
257- `keepalive` (boolean, optional): Whether to keep the request alive after the page is unloaded.
258
259- `method` (string, optional): The HTTP method for the request. Options include 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', and 'CONNECT'.
260
261- `mode` (string, optional): The mode of the request. Options are the same as in `FetchConfiguration.mode`.
262
263- `redirect` (string, optional): The redirect behavior for the request. Options include 'error', 'follow', and 'manual'.
264
265- `referrer` (string, optional): The referrer URL for the request.
266
267- `referrerPolicy` (string, optional): The referrer policy for the request. For example, 'no-referrer', 'no-referrer-when-downgrade', or 'same-origin'.
268
269## Contributing
270
271You are welcome to contribute! If you are adding a feature or fixing a bug, please contribute to the [GitHub repository](https://github.com/SheikhAminul/es-fetcher/).
272
273
274## License
275
276es-fetcher is licensed under the [MIT license](https://github.com/SheikhAminul/es-fetcher/blob/main/LICENSE).
277
278
279## Author
280
281|[![@SheikhAminul](https://avatars.githubusercontent.com/u/25372039?v=4&s=96)](https://github.com/SheikhAminul)|
282|:---:|
283|[@SheikhAminul](https://github.com/SheikhAminul)|
\No newline at end of file