reqforge 0.6.0 → 0.8.0

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.
package/README.md CHANGED
@@ -11,22 +11,44 @@ npm install reqforge
11
11
  ## Quick Start
12
12
 
13
13
  ```javascript
14
- const { config, utils, request, Logger, auth } = require('reqforge');
14
+ const { config, request, retry } = require('reqforge');
15
15
 
16
- // Get the base URL for API requests
17
- const baseURL = config.getBaseURL();
18
- console.log(baseURL); // https://api.example.com/v1
19
-
20
- // Login
21
- auth.login('username', 'password')
22
- .then(data => console.log('Logged in:', data.token));
23
-
24
- // Make a GET request
25
- request.get('/users')
26
- .then(res => res.json())
16
+ // Make a request with automatic retry
17
+ retry.withRetry(() => {
18
+ return request.get('/users')
19
+ .then(res => res.json());
20
+ }, { maxRetries: 3, delay: 1000 })
27
21
  .then(data => console.log(data));
28
22
  ```
29
23
 
24
+ ## Retry Mechanism
25
+
26
+ The `retry` module provides:
27
+
28
+ - `withRetry(fn, options)` - Execute function with automatic retry
29
+ - `calculateBackoff(attempt, baseDelay, maxDelay)` - Calculate exponential backoff delay
30
+
31
+ ### Retry Options
32
+
33
+ | Option | Default | Description |
34
+ |--------|---------|-------------|
35
+ | `maxRetries` | 3 | Maximum number of retry attempts |
36
+ | `delay` | 1000 | Initial delay in milliseconds |
37
+ | `backoff` | 2 | Backoff multiplier |
38
+ | `shouldRetry` | `() => true` | Function to determine if retry should occur |
39
+
40
+ ## Error Handling
41
+
42
+ The `errors` module provides:
43
+
44
+ - `ReqForgeError` - Base error class
45
+ - `NetworkError` - Network request failures
46
+ - `TimeoutError` - Request timeout errors
47
+ - `AuthError` - Authentication failures
48
+ - `ValidationError` - Validation errors
49
+ - `ErrorCodes` - Error code constants
50
+ - `createErrorFromResponse(response)` - Create error from response
51
+
30
52
  ## Authentication
31
53
 
32
54
  The `auth` module provides:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reqforge",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "A lightweight, flexible HTTP client library with request interception, automatic retry, and logging capabilities, designed for modern web applications.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/errors.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Error handling module for ReqForge
3
+ * @module errors
4
+ */
5
+
6
+ /**
7
+ * Base error class for ReqForge
8
+ */
9
+ class ReqForgeError extends Error {
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.name = 'ReqForgeError';
13
+ this.code = code;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Network error
19
+ */
20
+ class NetworkError extends ReqForgeError {
21
+ constructor(message = 'Network request failed') {
22
+ super(message, 'NETWORK_ERROR');
23
+ this.name = 'NetworkError';
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Timeout error
29
+ */
30
+ class TimeoutError extends ReqForgeError {
31
+ constructor(message = 'Request timeout') {
32
+ super(message, 'TIMEOUT_ERROR');
33
+ this.name = 'TimeoutError';
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Authentication error
39
+ */
40
+ class AuthError extends ReqForgeError {
41
+ constructor(message = 'Authentication failed') {
42
+ super(message, 'AUTH_ERROR');
43
+ this.name = 'AuthError';
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Validation error
49
+ */
50
+ class ValidationError extends ReqForgeError {
51
+ constructor(message = 'Validation failed') {
52
+ super(message, 'VALIDATION_ERROR');
53
+ this.name = 'ValidationError';
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Error codes
59
+ */
60
+ const ErrorCodes = {
61
+ NETWORK_ERROR: 'NETWORK_ERROR',
62
+ TIMEOUT_ERROR: 'TIMEOUT_ERROR',
63
+ AUTH_ERROR: 'AUTH_ERROR',
64
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
65
+ UNKNOWN_ERROR: 'UNKNOWN_ERROR'
66
+ };
67
+
68
+ /**
69
+ * Create error from response
70
+ * @param {Response} response - Fetch response
71
+ * @returns {ReqForgeError} Appropriate error instance
72
+ */
73
+ function createErrorFromResponse(response) {
74
+ if (response.status === 401) {
75
+ return new AuthError('Unauthorized');
76
+ }
77
+ if (response.status === 403) {
78
+ return new AuthError('Forbidden');
79
+ }
80
+ if (response.status === 404) {
81
+ return new NetworkError('Resource not found');
82
+ }
83
+ if (response.status >= 500) {
84
+ return new NetworkError('Server error');
85
+ }
86
+ return new ReqForgeError('Request failed', 'REQUEST_ERROR');
87
+ }
88
+
89
+ module.exports = {
90
+ ReqForgeError,
91
+ NetworkError,
92
+ TimeoutError,
93
+ AuthError,
94
+ ValidationError,
95
+ ErrorCodes,
96
+ createErrorFromResponse
97
+ };
package/src/index.js CHANGED
@@ -8,11 +8,15 @@ const utils = require('./utils');
8
8
  const request = require('./request');
9
9
  const Logger = require('./logger');
10
10
  const auth = require('./auth');
11
+ const errors = require('./errors');
12
+ const retry = require('./retry');
11
13
 
12
14
  module.exports = {
13
15
  config,
14
16
  utils,
15
17
  request,
16
18
  Logger,
17
- auth
19
+ auth,
20
+ errors,
21
+ retry
18
22
  };
package/src/retry.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Retry mechanism module for ReqForge
3
+ * @module retry
4
+ */
5
+
6
+ /**
7
+ * Execute function with retry
8
+ * @param {Function} fn - Function to execute
9
+ * @param {Object} options - Retry options
10
+ * @returns {Promise} Result of the function
11
+ */
12
+ async function withRetry(fn, options = {}) {
13
+ const {
14
+ maxRetries = 3,
15
+ delay = 1000,
16
+ backoff = 2,
17
+ shouldRetry = () => true
18
+ } = options;
19
+
20
+ let lastError;
21
+ let currentDelay = delay;
22
+
23
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
24
+ try {
25
+ return await fn();
26
+ } catch (error) {
27
+ lastError = error;
28
+
29
+ if (attempt === maxRetries || !shouldRetry(error)) {
30
+ throw error;
31
+ }
32
+
33
+ await new Promise(resolve => setTimeout(resolve, currentDelay));
34
+ currentDelay *= backoff;
35
+ }
36
+ }
37
+
38
+ throw lastError;
39
+ }
40
+
41
+ /**
42
+ * Calculate exponential backoff delay
43
+ * @param {number} attempt - Current attempt number
44
+ * @param {number} baseDelay - Base delay in ms
45
+ * @param {number} maxDelay - Maximum delay in ms
46
+ * @returns {number} Delay in ms
47
+ */
48
+ function calculateBackoff(attempt, baseDelay = 1000, maxDelay = 30000) {
49
+ const delay = baseDelay * Math.pow(2, attempt);
50
+ return Math.min(delay, maxDelay);
51
+ }
52
+
53
+ module.exports = {
54
+ withRetry,
55
+ calculateBackoff
56
+ };