rust-fetch 1.0.0 โ†’ 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +191 -116
  2. package/package.json +2 -2
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
- # Rust Fetch - World-Class HTTP Client for WebAssembly
1
+ # rust-fetch
2
2
 
3
- [![License: MIT/Apache-2.0](https://img.shields.io/badge/License-MIT%2FApache--2.0-blue.svg)](LICENSE)
4
- [![Rust](https://img.shields.io/badge/rust-%23000000.svg?style=flat&logo=rust&logoColor=white)](https://www.rust-lang.org/)
3
+ [![npm version](https://img.shields.io/npm/v/rust-fetch.svg)](https://www.npmjs.com/package/rust-fetch)
4
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](LICENSE)
5
5
  [![WebAssembly](https://img.shields.io/badge/WebAssembly-654FF0?style=flat&logo=WebAssembly&logoColor=white)](https://webassembly.org/)
6
6
 
7
- A production-ready, world-class HTTP client library for WebAssembly with excellent error handling, retry logic, and a clean API design.
7
+ A high-performance, world-class HTTP client for JavaScript/TypeScript powered by WebAssembly. Built with Rust for blazing-fast, memory-safe HTTP operations in both browser and Node.js environments.
8
8
 
9
9
  ## ๐Ÿš€ Features
10
10
 
@@ -18,19 +18,14 @@ A production-ready, world-class HTTP client library for WebAssembly with excelle
18
18
 
19
19
  ## ๐Ÿ“ฆ Installation
20
20
 
21
- Add this to your `Cargo.toml`:
22
-
23
- ```toml
24
- [dependencies]
25
- rust-fetch = "1.0.0"
21
+ ```bash
22
+ npm install rust-fetch
26
23
  ```
27
24
 
28
- For WebAssembly projects, make sure to include:
25
+ or
29
26
 
30
- ```toml
31
- [dependencies]
32
- wasm-bindgen = "0.2"
33
- wasm-bindgen-futures = "0.4"
27
+ ```bash
28
+ yarn add rust-fetch
34
29
  ```
35
30
 
36
31
  ## ๐Ÿ”ง Usage
@@ -39,79 +34,78 @@ wasm-bindgen-futures = "0.4"
39
34
 
40
35
  For quick and easy HTTP requests:
41
36
 
42
- ```rust
43
- use rust_fetch::prelude::*;
37
+ ### WASM Client Example
38
+ How to use the imported `WasmClient` to make HTTP requests from the browser or Node.js environment:
44
39
 
45
- // Fetch JSON data
46
- let data = fetch_json("https://api.example.com/data").await?;
40
+ #### Simple GET Request
41
+ Here's how to make a simple GET request using `WasmClient`:
47
42
 
48
- // Fetch text/HTML
49
- let html = fetch_text("https://example.com").await?;
50
-
51
- // Advanced request with options
52
- let response = fetch_with_options(
53
- "https://api.example.com/users",
54
- "POST",
55
- headers_obj, // JavaScript headers object
56
- Some(r#"{"name": "John Doe"}"#.to_string()),
57
- ).await?;
58
- ```
43
+ ```javascript
44
+ import init, { WasmClient } from 'rust-fetch/client';
59
45
 
60
- ### Advanced Client API
46
+ await init();
61
47
 
62
- For more control and configuration:
63
-
64
- ```rust
65
- use rust_fetch::client::Client;
66
- use rust_fetch::types::RetryConfig;
67
- use std::time::Duration;
68
-
69
- // Create a configured client
70
- let client = Client::builder()
71
- .base_url("https://api.example.com")
72
- .default_header("Authorization", "Bearer token")
73
- .timeout(Duration::from_secs(10))
74
- .retry_config(RetryConfig {
75
- max_retries: 3,
76
- initial_delay: Duration::from_millis(100),
77
- ..Default::default()
78
- })
79
- .build()?;
80
-
81
- // Make requests
82
- let response = client
83
- .post("/users")
84
- .json(&serde_json::json!({
85
- "name": "Jane Doe",
86
- "email": "jane@example.com"
87
- }))?
88
- .send()
89
- .await?;
90
-
91
- // Access response data
92
- println!("Status: {}", response.status);
93
- if let Some(json) = response.json() {
94
- println!("Response: {:?}", json);
95
- }
48
+ const client = new WasmClient();
49
+
50
+ client.get('https://jsonplaceholder.typicode.com/posts/1')
51
+ .then(response => console.log(response))
52
+ .catch(error => console.error('Error:', error));
96
53
  ```
97
54
 
98
- ### WebAssembly JavaScript API
55
+ #### POST Request with JSON
56
+ Here's how to make a POST request with a JSON body:
57
+
58
+ ```javascript
59
+ const data = { title: 'foo', body: 'bar', userId: 1 };
60
+
61
+ client.post_json('https://jsonplaceholder.typicode.com/posts', data)
62
+ .then(response => console.log(response))
63
+ .catch(error => console.error('Error:', error));
64
+ ```
99
65
 
100
- When compiled to WebAssembly, the library exposes a JavaScript-friendly API:
66
+ ### Using Fetch Functions
101
67
 
102
68
  ```javascript
103
- import init, { WasmClient, fetch_json, fetch_text } from './rust_fetch.js';
69
+ import init, { fetch_json, fetch_text } from 'rust-fetch/client';
104
70
 
71
+ // Initialize WASM module
105
72
  await init();
106
73
 
107
- // Simple API
108
- const data = await fetch_json("https://api.example.com/data");
109
- const html = await fetch_text("https://example.com");
74
+ // Fetch JSON data
75
+ try {
76
+ const data = await fetch_json('https://api.example.com/data');
77
+ console.log('JSON data:', data);
78
+ } catch (error) {
79
+ console.error('Error fetching JSON:', error);
80
+ }
81
+
82
+ // Fetch text/HTML
83
+ try {
84
+ const html = await fetch_text('https://example.com');
85
+ console.log('HTML content:', html);
86
+ } catch (error) {
87
+ console.error('Error fetching HTML:', error);
88
+ }
89
+ ```
110
90
 
111
- // Client API
112
- const client = new WasmClient();
113
- const response = await client.get("https://api.example.com/users");
114
- console.log(response);
91
+ ### Advanced Client API
92
+
93
+ For more control and enhanced configurations, use the `fetch_with_options` to fine-tune HTTP requests:
94
+
95
+ #### Using Advanced Options
96
+ You can specify HTTP method, headers, and body:
97
+
98
+ ```javascript
99
+ import { fetch_with_options } from 'rust-fetch/client';
100
+
101
+ const url = 'https://jsonplaceholder.typicode.com/posts';
102
+ const method = 'POST';
103
+ const headers = { 'Content-Type': 'application/json' };
104
+ const body = JSON.stringify({ userId: 1, title: 'foo', body: 'bar' });
105
+
106
+ fetch_with_options(url, method, headers, body)
107
+ .then(response => console.log(response))
108
+ .catch(error => console.error('Error:', error));
115
109
  ```
116
110
 
117
111
  ## ๐Ÿ—๏ธ Architecture
@@ -127,66 +121,147 @@ The library is organized into several modules:
127
121
 
128
122
  The library provides rich error types that preserve context:
129
123
 
130
- ```rust
131
- use rust_fetch::error::{Error, Result};
132
-
133
- match fetch_json(url).await {
134
- Ok(data) => println!("Success: {:?}", data),
135
- Err(Error::Network { message, source }) => {
136
- eprintln!("Network error: {}", message);
137
- }
138
- Err(Error::Http { status, status_text, body }) => {
139
- eprintln!("HTTP {}: {}", status, status_text);
140
- }
141
- Err(e) => eprintln!("Other error: {}", e),
124
+ ```javascript
125
+ try {
126
+ const data = await fetch_json(url);
127
+ console.log('Success:', data);
128
+ } catch (error) {
129
+ // Error handling with detailed context
130
+ console.error('Failed to fetch:', error.message);
142
131
  }
143
132
  ```
144
133
 
145
- ### Request Building
134
+ ## API Reference
135
+
136
+ ### HTTP Functions
137
+
138
+ #### `fetch_json(url: string): Promise<any>`
139
+ Fetches JSON data from the specified URL and returns it as a JavaScript object.
140
+
141
+ ```javascript
142
+ import { fetch_json } from 'rust-fetch/client';
143
+
144
+ const data = await fetch_json('https://jsonplaceholder.typicode.com/todos/1');
145
+ ```
146
+
147
+ #### `fetch_text(url: string): Promise<string>`
148
+ Fetches text/HTML content from the specified URL and returns it as a string.
146
149
 
147
- The client provides a fluent API for building requests:
150
+ ```javascript
151
+ import { fetch_text } from 'rust-fetch/client';
148
152
 
149
- ```rust
150
- let response = client
151
- .request(Method::Put, "/users/123")
152
- .header("Content-Type", "application/json")
153
- .header("X-Custom-Header", "value")
154
- .timeout(Duration::from_secs(5))
155
- .json(&updated_user)?
156
- .send()
157
- .await?;
153
+ const html = await fetch_text('https://example.com');
158
154
  ```
159
155
 
160
- ## ๐Ÿงช Testing
156
+ #### `fetch_with_options(url: string, method: string, headers: object, body?: string): Promise<object>`
157
+ Advanced fetch function with full control over the request.
161
158
 
162
- Run tests for native target:
159
+ ```javascript
160
+ import { fetch_with_options } from 'rust-fetch/client';
161
+
162
+ const response = await fetch_with_options(
163
+ 'https://api.example.com/users',
164
+ 'POST',
165
+ { 'Content-Type': 'application/json' },
166
+ JSON.stringify({ name: 'John Doe' })
167
+ );
168
+ ```
163
169
 
164
- ```bash
165
- cargo test
170
+ ### WasmClient Class
171
+
172
+ #### `new WasmClient()`
173
+ Creates a new HTTP client instance.
174
+
175
+ ```javascript
176
+ const client = new WasmClient();
166
177
  ```
167
178
 
168
- Run tests for WebAssembly target:
179
+ #### `client.get(url: string): Promise<object>`
180
+ Performs a GET request.
169
181
 
170
- ```bash
171
- wasm-pack test --headless --chrome
182
+ ```javascript
183
+ const response = await client.get('https://api.example.com/data');
184
+ ```
185
+
186
+ #### `client.post_json(url: string, body: object): Promise<object>`
187
+ Performs a POST request with JSON body.
188
+
189
+ ```javascript
190
+ const response = await client.post_json('https://api.example.com/users', {
191
+ name: 'Jane Doe',
192
+ email: 'jane@example.com'
193
+ });
172
194
  ```
173
195
 
174
- ## ๐Ÿค Contributing
175
196
 
176
- Contributions are welcome! Please feel free to submit a Pull Request.
197
+ ## Performance Considerations
198
+
199
+ - The WASM module adds a small overhead for initialization (~100-200ms on first load)
200
+ - Once loaded, HTTP operations benefit from Rust's efficient memory management
201
+ - Best suited for applications that make multiple HTTP requests or need predictable performance
202
+
203
+ ## Browser Support
204
+
205
+ - Chrome 57+
206
+ - Firefox 52+
207
+ - Safari 11+
208
+ - Edge 16+
209
+ - Node.js 14+
210
+
211
+ ## Contributing
212
+
213
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
214
+
215
+ 1. Fork the repository
216
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
217
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
218
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
219
+ 5. Open a Pull Request
220
+
221
+ ## License
222
+
223
+ This project is licensed under the ISC License - see the LICENSE file for details.
224
+
225
+ ## Troubleshooting
226
+
227
+ ### WASM Module Not Loading
228
+
229
+ If you encounter issues with the WASM module not loading:
230
+
231
+ 1. Ensure your server supports the `application/wasm` MIME type
232
+ 2. Check that the WASM file is being served correctly
233
+ 3. Verify you're awaiting the `initWasm()` call before using any functions
234
+
235
+ ### CORS Issues
236
+
237
+ When fetching from external APIs, ensure:
238
+
239
+ 1. The target server allows CORS requests
240
+ 2. You're using HTTPS URLs in production
241
+ 3. Consider using a proxy server for APIs that don't support CORS
242
+
243
+ ### Node.js Path Issues
177
244
 
178
- ## ๐Ÿ“„ License
245
+ If you encounter path resolution issues in Node.js:
179
246
 
180
- This project is licensed under either of
247
+ 1. Ensure the package is installed correctly
248
+ 2. Check that the WASM file exists in `node_modules/rust-fetch/wasm-module/pkg/`
249
+ 3. Try reinstalling the package
181
250
 
182
- - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
183
- - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
251
+ ## Acknowledgments
184
252
 
185
- at your option.
253
+ - Built with [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen)
254
+ - Uses [reqwest](https://github.com/seanmonstar/reqwest) for HTTP operations
255
+ - Inspired by the Rust and WebAssembly community
186
256
 
187
- ## ๐Ÿ™ Acknowledgments
257
+ ## Roadmap
188
258
 
189
- Built with love using:
190
- - [reqwest](https://github.com/seanmonstar/reqwest) - HTTP client
191
- - [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) - WebAssembly bindings
192
- - [serde](https://github.com/serde-rs/serde) - Serialization framework
259
+ - [ ] Add support for POST, PUT, DELETE methods
260
+ - [ ] Implement request headers customization
261
+ - [ ] Add streaming support for large responses
262
+ - [ ] Implement request cancellation
263
+ - [ ] Add comprehensive test suite
264
+ - [ ] Performance benchmarks against native fetch
265
+ - [ ] Support for form data and file uploads
266
+ - [ ] WebSocket support
267
+ - [ ] Request/response interceptors
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "Asem Qaffaf <asem@qaffaf.com>"
6
6
  ],
7
7
  "description": "A world-class WebAssembly HTTP client library with excellent error handling and clean API",
8
- "version": "1.0.0",
8
+ "version": "1.0.2",
9
9
  "license": "MIT OR Apache-2.0",
10
10
  "repository": {
11
11
  "type": "git",
@@ -28,4 +28,4 @@
28
28
  "fetch",
29
29
  "webassembly"
30
30
  ]
31
- }
31
+ }