rust-fetch 1.0.1 → 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 +120 -141
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,16 +1,22 @@
1
1
  # rust-fetch
2
2
 
3
- A WebAssembly-powered HTTP client library for JavaScript/TypeScript applications, built with Rust. This library provides fast, memory-safe HTTP operations through WebAssembly bindings, allowing you to leverage Rust's performance and safety guarantees in your web applications.
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
+ [![WebAssembly](https://img.shields.io/badge/WebAssembly-654FF0?style=flat&logo=WebAssembly&logoColor=white)](https://webassembly.org/)
4
6
 
5
- ## Features
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.
6
8
 
7
- - 🚀 **High Performance**: Leverage Rust's performance for HTTP operations through WebAssembly
8
- - 🔐 **Memory Safe**: Built with Rust's memory safety guarantees
9
- - 🌐 **Cross-Platform**: Works in both browser and Node.js environments
10
- - 📦 **TypeScript Support**: Full TypeScript definitions included
11
- - 🛠️ **Multiple Utilities**: HTTP fetching, JSON parsing, HTML retrieval, and utility functions
9
+ ## 🚀 Features
12
10
 
13
- ## Installation
11
+ - **Type-safe HTTP Client**: Builder pattern for constructing requests with compile-time safety
12
+ - **Comprehensive Error Handling**: Detailed error types with context and proper error chaining
13
+ - **Automatic Retries**: Built-in retry logic with exponential backoff for transient failures
14
+ - **Multiple Response Formats**: Support for JSON, text, and binary responses
15
+ - **Platform Optimized**: Specific optimizations for both WASM and native targets
16
+ - **Developer Friendly**: Clean API with both simple functions and advanced client builders
17
+ - **Backward Compatible**: Maintains compatibility with legacy API while providing modern alternatives
18
+
19
+ ## 📦 Installation
14
20
 
15
21
  ```bash
16
22
  npm install rust-fetch
@@ -22,199 +28,172 @@ or
22
28
  yarn add rust-fetch
23
29
  ```
24
30
 
25
- ## Project Structure
31
+ ## 🔧 Usage
26
32
 
27
- ```
28
- rust-fetch/
29
- ├── rust-fetch-package/ # Main Rust package (currently basic implementation)
30
- │ ├── Cargo.toml
31
- │ └── src/
32
- │ └── lib.rs
33
- ├── wasm-module/ # WebAssembly module with HTTP and utility functions
34
- │ ├── Cargo.toml
35
- │ ├── pkg/ # Generated WASM package
36
- │ └── src/
37
- │ ├── greetings/ # Greeting utilities
38
- │ ├── http/ # HTTP client functions
39
- │ ├── math/ # Math utilities
40
- │ └── lib.rs
41
- ├── client.ts # Client-side entry point
42
- ├── server.ts # Server-side entry point
43
- ├── package.json # NPM package configuration
44
- └── tsconfig.json # TypeScript configuration
45
- ```
33
+ ### Simple API
46
34
 
47
- ## Usage
35
+ For quick and easy HTTP requests:
48
36
 
49
- ### Client-Side (Browser)
37
+ ### WASM Client Example
38
+ How to use the imported `WasmClient` to make HTTP requests from the browser or Node.js environment:
50
39
 
51
- ```typescript
52
- import initWasm, {
53
- fetch_wasm_json,
54
- fetch_wasm_html,
55
- greet,
56
- add
57
- } from 'rust-fetch/client';
40
+ #### Simple GET Request
41
+ Here's how to make a simple GET request using `WasmClient`:
58
42
 
59
- // Initialize WASM module
60
- await initWasm();
43
+ ```javascript
44
+ import init, { WasmClient } from 'rust-fetch/client';
61
45
 
62
- // Fetch JSON data
63
- try {
64
- const data = await fetch_wasm_json('https://api.example.com/data');
65
- console.log('JSON data:', data);
66
- } catch (error) {
67
- console.error('Error fetching JSON:', error);
68
- }
46
+ await init();
69
47
 
70
- // Fetch HTML content
71
- try {
72
- const html = await fetch_wasm_html('https://example.com');
73
- console.log('HTML content:', html);
74
- } catch (error) {
75
- console.error('Error fetching HTML:', error);
76
- }
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));
53
+ ```
54
+
55
+ #### POST Request with JSON
56
+ Here's how to make a POST request with a JSON body:
77
57
 
78
- // Use utility functions
79
- const greeting = greet('World');
80
- console.log(greeting); // "Hello, World!"
58
+ ```javascript
59
+ const data = { title: 'foo', body: 'bar', userId: 1 };
81
60
 
82
- const sum = add(5, 3);
83
- console.log(sum); // 8
61
+ client.post_json('https://jsonplaceholder.typicode.com/posts', data)
62
+ .then(response => console.log(response))
63
+ .catch(error => console.error('Error:', error));
84
64
  ```
85
65
 
86
- ### Server-Side (Node.js)
66
+ ### Using Fetch Functions
87
67
 
88
- ```typescript
89
- import initWasm, {
90
- fetch_wasm_json,
91
- fetch_wasm_html,
92
- greet,
93
- add
94
- } from 'rust-fetch/server';
68
+ ```javascript
69
+ import init, { fetch_json, fetch_text } from 'rust-fetch/client';
95
70
 
96
- // WASM is automatically initialized on import
71
+ // Initialize WASM module
72
+ await init();
97
73
 
98
74
  // Fetch JSON data
99
75
  try {
100
- const data = await fetch_wasm_json('https://api.example.com/data');
76
+ const data = await fetch_json('https://api.example.com/data');
101
77
  console.log('JSON data:', data);
102
78
  } catch (error) {
103
79
  console.error('Error fetching JSON:', error);
104
80
  }
105
81
 
106
- // Use other functions similarly
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
+ }
107
89
  ```
108
90
 
109
- ## API Reference
91
+ ### Advanced Client API
110
92
 
111
- ### HTTP Functions
93
+ For more control and enhanced configurations, use the `fetch_with_options` to fine-tune HTTP requests:
112
94
 
113
- #### `fetch_wasm_json(url: string): Promise<any>`
114
- Fetches JSON data from the specified URL and returns it as a JavaScript object.
95
+ #### Using Advanced Options
96
+ You can specify HTTP method, headers, and body:
115
97
 
116
- ```typescript
117
- const data = await fetch_wasm_json('https://jsonplaceholder.typicode.com/todos/1');
118
- ```
98
+ ```javascript
99
+ import { fetch_with_options } from 'rust-fetch/client';
119
100
 
120
- #### `fetch_wasm_json_new(url: string): Promise<any>`
121
- Alternative implementation that returns a Promise directly (useful for different async patterns).
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' });
122
105
 
123
- ```typescript
124
- const promise = fetch_wasm_json_new('https://api.example.com/data');
125
- const data = await promise;
106
+ fetch_with_options(url, method, headers, body)
107
+ .then(response => console.log(response))
108
+ .catch(error => console.error('Error:', error));
126
109
  ```
127
110
 
128
- #### `fetch_wasm_map(url: string): Promise<any>`
129
- Fetches JSON data and returns it as a JavaScript object using `serde_wasm_bindgen`.
111
+ ## 🏗️ Architecture
130
112
 
131
- ```typescript
132
- const data = await fetch_wasm_map('https://api.example.com/data');
133
- ```
113
+ The library is organized into several modules:
134
114
 
135
- #### `fetch_wasm_html(url: string): Promise<string>`
136
- Fetches HTML content from the specified URL and returns it as a string.
115
+ - **`error`**: Comprehensive error types with detailed context
116
+ - **`types`**: Core types like `Method`, `Headers`, `Response`, etc.
117
+ - **`client`**: The main HTTP client with builder pattern
118
+ - **`http`**: High-level convenience functions for common use cases
137
119
 
138
- ```typescript
139
- const html = await fetch_wasm_html('https://example.com');
140
- ```
120
+ ### Error Handling
141
121
 
142
- #### `fetch_wasm_api(): Promise<any>`
143
- Fetches data from a predefined API endpoint (JSONPlaceholder todo item).
122
+ The library provides rich error types that preserve context:
144
123
 
145
- ```typescript
146
- const todo = await fetch_wasm_api();
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);
131
+ }
147
132
  ```
148
133
 
149
- ### Utility Functions
134
+ ## API Reference
150
135
 
151
- #### `greet(name: string): string`
152
- Returns a greeting message.
136
+ ### HTTP Functions
153
137
 
154
- ```typescript
155
- const message = greet('Alice'); // "Hello, Alice!"
156
- ```
138
+ #### `fetch_json(url: string): Promise<any>`
139
+ Fetches JSON data from the specified URL and returns it as a JavaScript object.
157
140
 
158
- #### `add(a: number, b: number): number`
159
- Adds two numbers together.
141
+ ```javascript
142
+ import { fetch_json } from 'rust-fetch/client';
160
143
 
161
- ```typescript
162
- const result = add(10, 20); // 30
144
+ const data = await fetch_json('https://jsonplaceholder.typicode.com/todos/1');
163
145
  ```
164
146
 
165
- ## Building from Source
147
+ #### `fetch_text(url: string): Promise<string>`
148
+ Fetches text/HTML content from the specified URL and returns it as a string.
166
149
 
167
- ### Prerequisites
150
+ ```javascript
151
+ import { fetch_text } from 'rust-fetch/client';
168
152
 
169
- - Rust (latest stable version)
170
- - Node.js (v14 or higher)
171
- - wasm-pack (`cargo install wasm-pack`)
172
-
173
- ### Build Steps
174
-
175
- 1. Clone the repository:
176
- ```bash
177
- git clone https://github.com/yourusername/rust-fetch.git
178
- cd rust-fetch
153
+ const html = await fetch_text('https://example.com');
179
154
  ```
180
155
 
181
- 2. Install dependencies:
182
- ```bash
183
- npm install
184
- ```
156
+ #### `fetch_with_options(url: string, method: string, headers: object, body?: string): Promise<object>`
157
+ Advanced fetch function with full control over the request.
185
158
 
186
- 3. Build the WASM module:
187
- ```bash
188
- npm run build:wasm
189
- ```
159
+ ```javascript
160
+ import { fetch_with_options } from 'rust-fetch/client';
190
161
 
191
- 4. Build TypeScript files:
192
- ```bash
193
- npm run build
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
+ );
194
168
  ```
195
169
 
196
- ## Development
170
+ ### WasmClient Class
197
171
 
198
- ### Building the WASM Module
172
+ #### `new WasmClient()`
173
+ Creates a new HTTP client instance.
199
174
 
200
- ```bash
201
- cd wasm-module
202
- wasm-pack build --target web
175
+ ```javascript
176
+ const client = new WasmClient();
203
177
  ```
204
178
 
205
- This generates the `pkg` directory with JavaScript bindings and TypeScript definitions.
179
+ #### `client.get(url: string): Promise<object>`
180
+ Performs a GET request.
206
181
 
207
- ### Running Tests
182
+ ```javascript
183
+ const response = await client.get('https://api.example.com/data');
184
+ ```
208
185
 
209
- For Rust tests:
210
- ```bash
211
- cd wasm-module
212
- cargo test
186
+ #### `client.post_json(url: string, body: object): Promise<object>`
187
+ Performs a POST request with JSON body.
213
188
 
214
- cd ../rust-fetch-package
215
- cargo test
189
+ ```javascript
190
+ const response = await client.post_json('https://api.example.com/users', {
191
+ name: 'Jane Doe',
192
+ email: 'jane@example.com'
193
+ });
216
194
  ```
217
195
 
196
+
218
197
  ## Performance Considerations
219
198
 
220
199
  - The WASM module adds a small overhead for initialization (~100-200ms on first load)
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.1",
8
+ "version": "1.0.2",
9
9
  "license": "MIT OR Apache-2.0",
10
10
  "repository": {
11
11
  "type": "git",