odesli.js 1.3.4 โ 1.3.6
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/.github/dependabot.yml +56 -0
- package/.github/workflows/dependabot-auto-merge.yml +137 -0
- package/API_IMPROVEMENTS.md +16 -16
- package/README.md +468 -85
- package/RELEASE_NOTES_1.1.0.md +1 -1
- package/examples/README.md +281 -60
- package/examples/advanced-features-example.js +4 -4
- package/examples/advanced-usage.js +3 -3
- package/examples/basic-usage.js +4 -9
- package/examples/cache-test.js +1 -1
- package/examples/rate-limiter-strategies.js +83 -0
- package/examples/test-apple-music-extraction.js +1 -1
- package/examples/user-agent-example.js +1 -1
- package/lib/rate-limiter.js +16 -15
- package/package.json +17 -5
- package/scripts/version-bump.js +41 -0
package/RELEASE_NOTES_1.1.0.md
CHANGED
package/examples/README.md
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
# Odesli.js Examples
|
|
2
2
|
|
|
3
|
-
This directory contains examples demonstrating how to use the Odesli.js library.
|
|
3
|
+
This directory contains comprehensive examples demonstrating how to use the Odesli.js library and its advanced features.
|
|
4
4
|
|
|
5
|
-
## Examples
|
|
5
|
+
## Examples Overview
|
|
6
6
|
|
|
7
7
|
### Basic Usage (`basic-usage.js`)
|
|
8
8
|
|
|
9
|
-
Demonstrates
|
|
9
|
+
Demonstrates fundamental usage patterns for both CommonJS and ESM:
|
|
10
10
|
|
|
11
11
|
- Single URL fetching
|
|
12
12
|
- Batch URL fetching with the unified API
|
|
13
13
|
- Basic error handling
|
|
14
|
+
- Country-specific requests
|
|
15
|
+
- Platform detection utilities
|
|
14
16
|
|
|
15
17
|
```bash
|
|
16
18
|
node examples/basic-usage.js
|
|
@@ -20,14 +22,12 @@ node examples/basic-usage.js
|
|
|
20
22
|
|
|
21
23
|
Shows advanced features and configurations:
|
|
22
24
|
|
|
23
|
-
- Custom client configuration
|
|
25
|
+
- Custom client configuration with all options
|
|
24
26
|
- Platform detection and ID extraction
|
|
25
|
-
- Cache management
|
|
27
|
+
- Cache management and statistics
|
|
26
28
|
- Unified fetch API for both single and batch operations
|
|
27
|
-
- Error handling and recovery
|
|
28
|
-
-
|
|
29
|
-
- **NEW**: Metrics collection
|
|
30
|
-
- **NEW**: Plugin system demonstration
|
|
29
|
+
- Error handling and recovery strategies
|
|
30
|
+
- Performance optimization techniques
|
|
31
31
|
|
|
32
32
|
```bash
|
|
33
33
|
node examples/advanced-usage.js
|
|
@@ -37,35 +37,75 @@ node examples/advanced-usage.js
|
|
|
37
37
|
|
|
38
38
|
Comprehensive demonstration of enterprise-grade features:
|
|
39
39
|
|
|
40
|
-
- Rate limiting with
|
|
40
|
+
- Rate limiting with all three strategies (token bucket, sliding window, leaky bucket)
|
|
41
41
|
- Comprehensive metrics collection and analysis
|
|
42
|
-
- Plugin system with hooks and
|
|
42
|
+
- Plugin system with hooks, middleware, and transformers
|
|
43
43
|
- Error handling with plugins
|
|
44
|
-
- Performance monitoring
|
|
44
|
+
- Performance monitoring and optimization
|
|
45
45
|
|
|
46
46
|
```bash
|
|
47
47
|
node examples/advanced-features-example.js
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
+
### Rate Limiter Strategies (`rate-limiter-strategies.js`)
|
|
51
|
+
|
|
52
|
+
Detailed comparison and usage of all rate limiting strategies:
|
|
53
|
+
|
|
54
|
+
- Token Bucket: Burst handling with configurable capacity
|
|
55
|
+
- Sliding Window: Precise timing with no overages
|
|
56
|
+
- Leaky Bucket: Traffic smoothing with queue management
|
|
57
|
+
- Performance comparisons and timing demonstrations
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
node examples/rate-limiter-strategies.js
|
|
61
|
+
```
|
|
62
|
+
|
|
50
63
|
### User-Agent Example (`user-agent-example.js`)
|
|
51
64
|
|
|
52
|
-
Shows how to work with User-Agent headers:
|
|
65
|
+
Shows how to work with User-Agent headers and custom configurations:
|
|
53
66
|
|
|
54
67
|
- Default User-Agent generation
|
|
55
68
|
- Custom header overrides
|
|
56
69
|
- Platform and version information
|
|
70
|
+
- Browser-like User-Agent strings
|
|
57
71
|
|
|
58
72
|
```bash
|
|
59
73
|
node examples/user-agent-example.js
|
|
60
74
|
```
|
|
61
75
|
|
|
76
|
+
## Import Examples
|
|
77
|
+
|
|
78
|
+
### CommonJS (require)
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
// Main library
|
|
82
|
+
const Odesli = require('odesli.js');
|
|
83
|
+
|
|
84
|
+
// Extensions
|
|
85
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
86
|
+
const { MetricsCollector } = require('odesli.js/metrics');
|
|
87
|
+
const { PluginSystem } = require('odesli.js/plugin-system');
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### ESM (import)
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
// Main library
|
|
94
|
+
import Odesli from 'odesli.js';
|
|
95
|
+
|
|
96
|
+
// Extensions
|
|
97
|
+
import { RateLimiter } from 'odesli.js/rate-limiter';
|
|
98
|
+
import { MetricsCollector } from 'odesli.js/metrics';
|
|
99
|
+
import { PluginSystem } from 'odesli.js/plugin-system';
|
|
100
|
+
```
|
|
101
|
+
|
|
62
102
|
## Key Features Demonstrated
|
|
63
103
|
|
|
64
104
|
### Unified Fetch API
|
|
65
105
|
|
|
66
|
-
The `fetch()` method
|
|
106
|
+
The `fetch()` method supports both single URLs and arrays of URLs with comprehensive options:
|
|
67
107
|
|
|
68
|
-
```
|
|
108
|
+
```js
|
|
69
109
|
// Single fetch
|
|
70
110
|
const song = await odesli.fetch('https://open.spotify.com/track/123');
|
|
71
111
|
|
|
@@ -75,141 +115,266 @@ const songs = await odesli.fetch([
|
|
|
75
115
|
'https://open.spotify.com/track/456',
|
|
76
116
|
]);
|
|
77
117
|
|
|
78
|
-
// Batch fetch with options
|
|
118
|
+
// Batch fetch with advanced options
|
|
79
119
|
const songs = await odesli.fetch(urls, {
|
|
80
120
|
country: 'GB',
|
|
81
121
|
concurrency: 3,
|
|
82
122
|
skipCache: true,
|
|
123
|
+
timeout: 5000,
|
|
83
124
|
});
|
|
84
125
|
```
|
|
85
126
|
|
|
86
127
|
### Rate Limiting
|
|
87
128
|
|
|
88
|
-
Built-in rate limiting with
|
|
129
|
+
Built-in rate limiting with three strategies and auto-queue functionality:
|
|
89
130
|
|
|
90
|
-
```
|
|
91
|
-
const RateLimiter = require('
|
|
131
|
+
```js
|
|
132
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
92
133
|
|
|
93
|
-
|
|
94
|
-
|
|
134
|
+
// Sliding Window (recommended for API compliance)
|
|
135
|
+
const limiter = new RateLimiter({
|
|
136
|
+
maxRequests: 8, // Stay under the 10/minute API limit
|
|
95
137
|
windowMs: 60000, // 1 minute
|
|
96
|
-
strategy: '
|
|
138
|
+
strategy: 'sliding-window',
|
|
97
139
|
});
|
|
98
140
|
|
|
99
|
-
//
|
|
100
|
-
|
|
101
|
-
|
|
141
|
+
// Auto-queue all requests
|
|
142
|
+
async function fetchWithRateLimit(url, index) {
|
|
143
|
+
await limiter.waitForSlot();
|
|
144
|
+
return await odesli.fetch(url);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Submit all requests at once - they'll be processed automatically
|
|
148
|
+
const promises = urls.map((url, index) => fetchWithRateLimit(url, index));
|
|
149
|
+
const results = await Promise.all(promises);
|
|
102
150
|
```
|
|
103
151
|
|
|
104
152
|
### Metrics Collection
|
|
105
153
|
|
|
106
|
-
Comprehensive metrics tracking:
|
|
154
|
+
Comprehensive metrics tracking with real-time analysis:
|
|
107
155
|
|
|
108
|
-
```
|
|
109
|
-
const MetricsCollector = require('
|
|
156
|
+
```js
|
|
157
|
+
const { MetricsCollector } = require('odesli.js/metrics');
|
|
110
158
|
|
|
111
159
|
const metrics = new MetricsCollector({
|
|
112
160
|
enabled: true,
|
|
113
161
|
retentionMs: 24 * 60 * 60 * 1000, // 24 hours
|
|
162
|
+
maxDataPoints: 10000,
|
|
114
163
|
});
|
|
115
164
|
|
|
116
|
-
// Record request
|
|
165
|
+
// Record request with full context
|
|
117
166
|
metrics.recordRequest({
|
|
118
|
-
url: 'https://
|
|
167
|
+
url: 'https://api.song.link/v1-alpha.1/links',
|
|
168
|
+
method: 'GET',
|
|
119
169
|
startTime: Date.now(),
|
|
170
|
+
endTime: Date.now() + 150,
|
|
120
171
|
success: true,
|
|
172
|
+
statusCode: 200,
|
|
173
|
+
responseTime: 150,
|
|
121
174
|
platform: 'spotify',
|
|
122
175
|
country: 'US',
|
|
176
|
+
cacheHit: false,
|
|
123
177
|
});
|
|
124
178
|
|
|
125
|
-
// Get summary
|
|
179
|
+
// Get comprehensive summary
|
|
126
180
|
const summary = metrics.getSummary();
|
|
127
|
-
console.log(
|
|
181
|
+
console.log(
|
|
182
|
+
'Success Rate:',
|
|
183
|
+
(summary.rates.successRate * 100).toFixed(1) + '%'
|
|
184
|
+
);
|
|
185
|
+
console.log(
|
|
186
|
+
'Cache Hit Rate:',
|
|
187
|
+
(summary.rates.cacheHitRate * 100).toFixed(1) + '%'
|
|
188
|
+
);
|
|
189
|
+
console.log('Average Response Time:', summary.recent.avgResponseTime + 'ms');
|
|
128
190
|
```
|
|
129
191
|
|
|
130
192
|
### Plugin System
|
|
131
193
|
|
|
132
|
-
Extensible functionality through
|
|
133
|
-
|
|
134
|
-
```
|
|
135
|
-
const { PluginSystem
|
|
194
|
+
Extensible functionality through hooks, middleware, and transformers:
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
const { PluginSystem } = require('odesli.js/plugin-system');
|
|
198
|
+
|
|
199
|
+
const plugins = new PluginSystem();
|
|
200
|
+
|
|
201
|
+
// Register a logging plugin
|
|
202
|
+
plugins.registerPlugin('logger', {
|
|
203
|
+
hooks: {
|
|
204
|
+
beforeRequest: context => {
|
|
205
|
+
console.log(`๐ Requesting: ${context.url}`);
|
|
206
|
+
},
|
|
207
|
+
afterRequest: context => {
|
|
208
|
+
console.log(`โ
Completed: ${context.url} (${context.responseTime}ms)`);
|
|
209
|
+
},
|
|
210
|
+
onError: context => {
|
|
211
|
+
console.log(`โ Error: ${context.error.message}`);
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
});
|
|
136
215
|
|
|
137
|
-
|
|
138
|
-
|
|
216
|
+
// Register middleware for authentication
|
|
217
|
+
plugins.registerPlugin('auth', {
|
|
218
|
+
middleware: async (context, next) => {
|
|
219
|
+
context.headers = context.headers || {};
|
|
220
|
+
context.headers['Authorization'] = 'Bearer your-api-key';
|
|
221
|
+
return await next();
|
|
222
|
+
},
|
|
223
|
+
});
|
|
139
224
|
|
|
140
|
-
// Execute hooks
|
|
141
|
-
await
|
|
225
|
+
// Execute hooks and middleware
|
|
226
|
+
await plugins.executeHook('beforeRequest', {
|
|
227
|
+
url: 'https://api.song.link/test',
|
|
228
|
+
});
|
|
142
229
|
```
|
|
143
230
|
|
|
144
231
|
### Error Handling
|
|
145
232
|
|
|
146
|
-
|
|
233
|
+
Robust error handling for both single and batch operations:
|
|
234
|
+
|
|
235
|
+
```js
|
|
236
|
+
// Single request with error handling
|
|
237
|
+
try {
|
|
238
|
+
const song = await odesli.fetch('https://open.spotify.com/track/123');
|
|
239
|
+
console.log(`Success: ${song.title}`);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
console.error(`Error: ${error.message}`);
|
|
242
|
+
}
|
|
147
243
|
|
|
148
|
-
|
|
244
|
+
// Batch requests with graceful error handling
|
|
149
245
|
const results = await odesli.fetch(urls);
|
|
150
246
|
results.forEach((result, index) => {
|
|
151
247
|
if (result.error) {
|
|
152
248
|
console.log(`Song ${index + 1}: Error - ${result.error}`);
|
|
249
|
+
console.log(` Platform: ${result.platform}`);
|
|
250
|
+
console.log(` Status: ${result.statusCode}`);
|
|
251
|
+
console.log(` Suggestion: ${result.suggestion}`);
|
|
153
252
|
} else {
|
|
154
253
|
console.log(`Song ${index + 1}: ${result.title}`);
|
|
155
254
|
}
|
|
156
255
|
});
|
|
157
256
|
```
|
|
158
257
|
|
|
159
|
-
### Platform Detection
|
|
258
|
+
### Platform Detection and Utilities
|
|
160
259
|
|
|
161
|
-
Utility methods for working with URLs:
|
|
260
|
+
Utility methods for working with URLs and platforms:
|
|
162
261
|
|
|
163
|
-
```
|
|
262
|
+
```js
|
|
263
|
+
// Detect platform from URL
|
|
164
264
|
const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
|
|
265
|
+
console.log('Platform:', platform); // 'spotify'
|
|
266
|
+
|
|
267
|
+
// Extract ID from URL
|
|
165
268
|
const id = odesli.extractId('https://open.spotify.com/track/123');
|
|
269
|
+
console.log('ID:', id); // '123'
|
|
270
|
+
|
|
271
|
+
// Get supported platforms
|
|
272
|
+
const platforms = odesli.getSupportedPlatforms();
|
|
273
|
+
console.log('Supported platforms:', platforms);
|
|
274
|
+
|
|
275
|
+
// Get country options for UI dropdowns
|
|
276
|
+
const countries = Odesli.getCountryOptions();
|
|
277
|
+
console.log('Available countries:', countries.length);
|
|
166
278
|
```
|
|
167
279
|
|
|
168
280
|
## Advanced Features
|
|
169
281
|
|
|
170
282
|
### Rate Limiting Strategies
|
|
171
283
|
|
|
172
|
-
1. **Token Bucket** (
|
|
173
|
-
|
|
174
|
-
|
|
284
|
+
1. **Token Bucket** (Burst Handling):
|
|
285
|
+
|
|
286
|
+
```js
|
|
287
|
+
const limiter = new RateLimiter({
|
|
288
|
+
maxRequests: 10,
|
|
289
|
+
windowMs: 60000,
|
|
290
|
+
strategy: 'token-bucket',
|
|
291
|
+
burstCapacity: 15, // Allow bursts up to 15 requests
|
|
292
|
+
});
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
2. **Sliding Window** (Precise Timing - Recommended):
|
|
296
|
+
|
|
297
|
+
```js
|
|
298
|
+
const limiter = new RateLimiter({
|
|
299
|
+
maxRequests: 8,
|
|
300
|
+
windowMs: 60000,
|
|
301
|
+
strategy: 'sliding-window',
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
3. **Leaky Bucket** (Traffic Smoothing):
|
|
306
|
+
|
|
307
|
+
```js
|
|
308
|
+
const limiter = new RateLimiter({
|
|
309
|
+
maxRequests: 3,
|
|
310
|
+
windowMs: 5000,
|
|
311
|
+
strategy: 'leaky-bucket',
|
|
312
|
+
queueSize: 10, // Limit queue to 10 pending requests
|
|
313
|
+
});
|
|
314
|
+
```
|
|
175
315
|
|
|
176
316
|
### Metrics Analysis
|
|
177
317
|
|
|
178
|
-
- **Real-time counters**: Total requests, success/failure rates
|
|
179
|
-
- **Performance metrics**: Response times, throughput
|
|
180
|
-
- **Cache analytics**: Hit rates, cache efficiency
|
|
318
|
+
- **Real-time counters**: Total requests, success/failure rates, cache hits/misses
|
|
319
|
+
- **Performance metrics**: Response times, throughput, requests per minute
|
|
320
|
+
- **Cache analytics**: Hit rates, cache efficiency, cache size
|
|
181
321
|
- **Platform analysis**: Usage by platform and country
|
|
182
|
-
- **Error tracking**: Error patterns and
|
|
322
|
+
- **Error tracking**: Error patterns, frequency, and suggestions
|
|
323
|
+
- **Rate limit monitoring**: Rate limit hits and average delays
|
|
183
324
|
|
|
184
325
|
### Plugin System Features
|
|
185
326
|
|
|
186
|
-
- **Hooks**: Execute code at specific points (beforeRequest, afterRequest, onError, etc.)
|
|
187
|
-
- **Middleware**: Process requests through a chain
|
|
188
|
-
- **Transformers**: Modify response data
|
|
327
|
+
- **Hooks**: Execute code at specific points (beforeRequest, afterRequest, onError, onRateLimit, etc.)
|
|
328
|
+
- **Middleware**: Process requests through a chain with context modification
|
|
329
|
+
- **Transformers**: Modify response data for different formats
|
|
189
330
|
- **Built-in plugins**: Logging, caching, analytics, response transformation
|
|
331
|
+
- **Priority system**: Control execution order of hooks
|
|
332
|
+
- **Error isolation**: Prevent plugin errors from breaking the system
|
|
190
333
|
|
|
191
334
|
## Running Examples
|
|
192
335
|
|
|
193
|
-
|
|
336
|
+
### Prerequisites
|
|
194
337
|
|
|
195
338
|
```bash
|
|
196
339
|
npm install
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### Basic Examples
|
|
343
|
+
|
|
344
|
+
```bash
|
|
345
|
+
# Basic usage
|
|
197
346
|
node examples/basic-usage.js
|
|
347
|
+
|
|
348
|
+
# Advanced usage
|
|
349
|
+
node examples/advanced-usage.js
|
|
350
|
+
|
|
351
|
+
# User agent examples
|
|
352
|
+
node examples/user-agent-example.js
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### Running Advanced Examples
|
|
356
|
+
|
|
357
|
+
```bash
|
|
358
|
+
# Comprehensive advanced features
|
|
359
|
+
node examples/advanced-features-example.js
|
|
360
|
+
|
|
361
|
+
# Rate limiter strategy comparison
|
|
362
|
+
node examples/rate-limiter-strategies.js
|
|
198
363
|
```
|
|
199
364
|
|
|
200
365
|
### Environment Variables
|
|
201
366
|
|
|
202
|
-
Some examples use environment variables:
|
|
367
|
+
Some examples use environment variables for API keys:
|
|
203
368
|
|
|
204
369
|
```bash
|
|
205
370
|
# Optional: Set API key for higher rate limits
|
|
206
371
|
export ODESLI_API_KEY=your-api-key-here
|
|
207
372
|
|
|
208
|
-
# Run
|
|
373
|
+
# Run examples with API key
|
|
209
374
|
node examples/advanced-features-example.js
|
|
210
375
|
```
|
|
211
376
|
|
|
212
|
-
### Testing
|
|
377
|
+
### Testing
|
|
213
378
|
|
|
214
379
|
Run the comprehensive test suite:
|
|
215
380
|
|
|
@@ -218,4 +383,60 @@ npm test
|
|
|
218
383
|
npm test -- --testNamePattern="Advanced Features"
|
|
219
384
|
```
|
|
220
385
|
|
|
221
|
-
|
|
386
|
+
## Example Output
|
|
387
|
+
|
|
388
|
+
### Rate Limiter Demo
|
|
389
|
+
|
|
390
|
+
```js
|
|
391
|
+
๐ Auto-Queue Rate Limiter Demo
|
|
392
|
+
๐ Limit: 2 requests per 3s
|
|
393
|
+
๐ Submitting 3 requests...
|
|
394
|
+
|
|
395
|
+
โณ Request 1: Waiting for slot...
|
|
396
|
+
โ
Request 1: Got slot, fetching...
|
|
397
|
+
๐ต Request 1: Bad and Boujee
|
|
398
|
+
|
|
399
|
+
โณ Request 2: Waiting for slot...
|
|
400
|
+
โ
Request 2: Got slot, fetching...
|
|
401
|
+
๐ต Request 2: Rockstar
|
|
402
|
+
|
|
403
|
+
โณ Request 3: Waiting for slot...
|
|
404
|
+
โ
Request 3: Got slot, fetching...
|
|
405
|
+
๐ต Request 3: Congratulations
|
|
406
|
+
|
|
407
|
+
๐ All requests completed!
|
|
408
|
+
๐ Total songs fetched: 3
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
### Metrics Summary
|
|
412
|
+
|
|
413
|
+
```js
|
|
414
|
+
๐ Metrics Summary:
|
|
415
|
+
Counters: {
|
|
416
|
+
totalRequests: 15,
|
|
417
|
+
successfulRequests: 14,
|
|
418
|
+
failedRequests: 1,
|
|
419
|
+
cacheHits: 3,
|
|
420
|
+
cacheMisses: 12,
|
|
421
|
+
rateLimitHits: 2
|
|
422
|
+
}
|
|
423
|
+
Recent Activity: {
|
|
424
|
+
requests: 15,
|
|
425
|
+
errors: 1,
|
|
426
|
+
avgResponseTime: '245ms',
|
|
427
|
+
requestsPerMinute: 0.25
|
|
428
|
+
}
|
|
429
|
+
Rates: {
|
|
430
|
+
successRate: '93.3%',
|
|
431
|
+
cacheHitRate: '20.0%',
|
|
432
|
+
errorRate: '6.7%'
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
## Notes
|
|
437
|
+
|
|
438
|
+
- Examples make actual API calls and may be subject to rate limiting without an API key
|
|
439
|
+
- Rate limiting examples demonstrate how to handle API limits gracefully
|
|
440
|
+
- All examples include comprehensive error handling
|
|
441
|
+
- Examples are designed to be copy-paste ready for production use
|
|
442
|
+
- Performance metrics are real and reflect actual API response times
|
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
// - Metrics Collector: Tracks requests, errors, and performance for analytics and debugging.
|
|
6
6
|
// - Plugin System: Lets you add hooks, middleware, and transformers for custom logic (logging, analytics, etc).
|
|
7
7
|
|
|
8
|
-
const Odesli = require('
|
|
9
|
-
const { RateLimiter } = require('
|
|
10
|
-
const { MetricsCollector } = require('
|
|
11
|
-
const { PluginSystem } = require('
|
|
8
|
+
const Odesli = require('odesli.js');
|
|
9
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
10
|
+
const { MetricsCollector } = require('odesli.js/metrics');
|
|
11
|
+
const { PluginSystem } = require('odesli.js/plugin-system');
|
|
12
12
|
|
|
13
13
|
async function advancedExample() {
|
|
14
14
|
console.log('=== Advanced Features Example ===\n');
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
|
|
2
|
-
const Odesli = require('
|
|
3
|
-
const { RateLimiter } = require('
|
|
2
|
+
const Odesli = require('odesli.js');
|
|
3
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
4
4
|
|
|
5
5
|
async function advancedExample() {
|
|
6
6
|
console.log('๐ Advanced Odesli.js Usage Example\n');
|
|
@@ -150,7 +150,7 @@ async function advancedExample() {
|
|
|
150
150
|
PluginSystem,
|
|
151
151
|
loggingPlugin,
|
|
152
152
|
analyticsPlugin,
|
|
153
|
-
} = require('
|
|
153
|
+
} = require('odesli.js/plugin-system');
|
|
154
154
|
const pluginSystem = new PluginSystem();
|
|
155
155
|
pluginSystem.registerPlugin('logging', loggingPlugin);
|
|
156
156
|
pluginSystem.registerPlugin('analytics', analyticsPlugin);
|
package/examples/basic-usage.js
CHANGED
|
@@ -1,16 +1,11 @@
|
|
|
1
1
|
// Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
|
|
2
|
-
const Odesli = require('
|
|
2
|
+
const Odesli = require('odesli.js');
|
|
3
3
|
// For ESM (import)
|
|
4
4
|
// import { Odesli } from '../lib/index.mjs';
|
|
5
5
|
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// const {
|
|
9
|
-
// const { MetricsCollector } = require('../lib/metrics');
|
|
10
|
-
|
|
11
|
-
// For ESM
|
|
12
|
-
// import { RateLimiter } from '../lib/rate-limiter.mjs';
|
|
13
|
-
// import { MetricsCollector } from '../lib/metrics.mjs';
|
|
6
|
+
// For advanced features, uncomment these lines:
|
|
7
|
+
// const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
8
|
+
// const { MetricsCollector } = require('odesli.js/metrics');
|
|
14
9
|
|
|
15
10
|
// Initialize without API key (public usage, rate-limited)
|
|
16
11
|
const odesli = new Odesli({
|
package/examples/cache-test.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Cache Test Example
|
|
2
2
|
// This example demonstrates how caching works by making the same request multiple times
|
|
3
|
-
const Odesli = require('
|
|
3
|
+
const Odesli = require('odesli.js');
|
|
4
4
|
|
|
5
5
|
async function cacheTest() {
|
|
6
6
|
console.log('๐งช Testing Cache Functionality\n');
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const Odesli = require('odesli.js');
|
|
2
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
3
|
+
const odesli = new Odesli();
|
|
4
|
+
|
|
5
|
+
// Test URLs
|
|
6
|
+
const urls = [
|
|
7
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
8
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
9
|
+
'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
|
|
10
|
+
'https://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6',
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
// Function to test a strategy
|
|
14
|
+
async function testStrategy(strategy, maxRequests, windowMs) {
|
|
15
|
+
console.log(`\n๐ง Testing ${strategy.toUpperCase()} Strategy`);
|
|
16
|
+
console.log(`๐ Config: ${maxRequests} requests per ${windowMs / 1000}s`);
|
|
17
|
+
console.log('โ'.repeat(50));
|
|
18
|
+
|
|
19
|
+
const limiter = new RateLimiter({
|
|
20
|
+
maxRequests,
|
|
21
|
+
windowMs,
|
|
22
|
+
strategy,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const startTime = Date.now();
|
|
26
|
+
|
|
27
|
+
// Submit all requests at once
|
|
28
|
+
const promises = urls.map(async (url, index) => {
|
|
29
|
+
const requestStart = Date.now();
|
|
30
|
+
console.log(`โณ Request ${index + 1}: Waiting for slot...`);
|
|
31
|
+
|
|
32
|
+
await limiter.waitForSlot();
|
|
33
|
+
const waitTime = Date.now() - requestStart;
|
|
34
|
+
|
|
35
|
+
console.log(`โ
Request ${index + 1}: Got slot (waited ${waitTime}ms)`);
|
|
36
|
+
const song = await odesli.fetch(url);
|
|
37
|
+
console.log(`๐ต Request ${index + 1}: ${song.title}`);
|
|
38
|
+
|
|
39
|
+
return { song, waitTime };
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const results = await Promise.all(promises);
|
|
43
|
+
const totalTime = Date.now() - startTime;
|
|
44
|
+
|
|
45
|
+
console.log(`\n๐ Results for ${strategy}:`);
|
|
46
|
+
console.log(`โฑ๏ธ Total time: ${totalTime}ms`);
|
|
47
|
+
console.log(
|
|
48
|
+
`๐ Average wait: ${Math.round(results.reduce((sum, r) => sum + r.waitTime, 0) / results.length)}ms`
|
|
49
|
+
);
|
|
50
|
+
console.log(`๐ฏ Strategy status:`, limiter.getStatus());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Test all strategies
|
|
54
|
+
(async () => {
|
|
55
|
+
console.log('๐ Rate Limiter Strategy Comparison');
|
|
56
|
+
console.log('='.repeat(60));
|
|
57
|
+
|
|
58
|
+
// 1. TOKEN BUCKET - Good for burst handling
|
|
59
|
+
await testStrategy('token-bucket', 2, 3000);
|
|
60
|
+
|
|
61
|
+
// 2. SLIDING WINDOW - Most accurate rate limiting
|
|
62
|
+
await testStrategy('sliding-window', 2, 3000);
|
|
63
|
+
|
|
64
|
+
// 3. LEAKY BUCKET - Good for smoothing traffic
|
|
65
|
+
await testStrategy('leaky-bucket', 2, 3000);
|
|
66
|
+
|
|
67
|
+
console.log('\n๐ Strategy Guide:');
|
|
68
|
+
console.log('='.repeat(60));
|
|
69
|
+
console.log('๐ฏ TOKEN BUCKET:');
|
|
70
|
+
console.log(' โ
Pros: Handles bursts well, efficient memory usage');
|
|
71
|
+
console.log(' โ Cons: Less precise timing, can allow slight overages');
|
|
72
|
+
console.log(' ๐ฏ Use when: You want to allow some burst traffic');
|
|
73
|
+
console.log('');
|
|
74
|
+
console.log('๐ SLIDING WINDOW:');
|
|
75
|
+
console.log(' โ
Pros: Most accurate, precise timing, no overages');
|
|
76
|
+
console.log(' โ Cons: More memory usage, slightly more complex');
|
|
77
|
+
console.log(' ๐ฏ Use when: You need exact rate limiting (recommended)');
|
|
78
|
+
console.log('');
|
|
79
|
+
console.log('๐ง LEAKY BUCKET:');
|
|
80
|
+
console.log(' โ
Pros: Smooths traffic, predictable output rate');
|
|
81
|
+
console.log(' โ Cons: Can delay requests, less responsive to bursts');
|
|
82
|
+
console.log(' ๐ฏ Use when: You want to smooth out traffic spikes');
|
|
83
|
+
})();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
|
|
2
|
-
const Odesli = require('
|
|
2
|
+
const Odesli = require('odesli.js');
|
|
3
3
|
|
|
4
4
|
async function userAgentExample() {
|
|
5
5
|
console.log('๐ Odesli.js User-Agent Example\n');
|