odesli.js 1.3.8 → 2.0.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 +97 -85
- package/lib/index.d.ts +114 -17
- package/lib/index.js +893 -201
- package/lib/index.mjs +6 -3
- package/package.json +11 -2
- package/.eslintrc.js +0 -33
- package/.gitattributes +0 -1
- package/.github/dependabot.yml +0 -56
- package/.github/workflows/ci.yml +0 -94
- package/.github/workflows/dependabot-auto-merge.yml +0 -137
- package/.github/workflows/publish-github-packages.yml +0 -46
- package/.github/workflows/publish-npm.yml +0 -49
- package/.prettierignore +0 -31
- package/.prettierrc +0 -11
- package/API_IMPROVEMENTS.md +0 -318
- package/CHANGELOG.md +0 -246
- package/CODE_OF_CONDUCT.md +0 -125
- package/CONTRIBUTING.md +0 -104
- package/RELEASE_NOTES_1.1.0.md +0 -84
- package/SECURITY.md +0 -112
- package/examples/README.md +0 -442
- package/examples/advanced-features-example.js +0 -205
- package/examples/advanced-usage.js +0 -247
- package/examples/basic-usage.js +0 -100
- package/examples/cache-test.js +0 -119
- package/examples/rate-limiter-strategies.js +0 -83
- package/examples/test-apple-music-extraction.js +0 -60
- package/examples/user-agent-example.js +0 -46
- package/jest.config.js +0 -14
- package/jsdoc.json +0 -24
- package/scripts/version-bump.js +0 -41
- package/tests/advanced-features.test.js +0 -423
- package/tests/odesli.test.js +0 -742
- package/tests/setup.js +0 -22
- package/tsconfig.json +0 -21
package/examples/README.md
DELETED
|
@@ -1,442 +0,0 @@
|
|
|
1
|
-
# Odesli.js Examples
|
|
2
|
-
|
|
3
|
-
This directory contains comprehensive examples demonstrating how to use the Odesli.js library and its advanced features.
|
|
4
|
-
|
|
5
|
-
## Examples Overview
|
|
6
|
-
|
|
7
|
-
### Basic Usage (`basic-usage.js`)
|
|
8
|
-
|
|
9
|
-
Demonstrates fundamental usage patterns for both CommonJS and ESM:
|
|
10
|
-
|
|
11
|
-
- Single URL fetching
|
|
12
|
-
- Batch URL fetching with the unified API
|
|
13
|
-
- Basic error handling
|
|
14
|
-
- Country-specific requests
|
|
15
|
-
- Platform detection utilities
|
|
16
|
-
|
|
17
|
-
```bash
|
|
18
|
-
node examples/basic-usage.js
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
### Advanced Usage (`advanced-usage.js`)
|
|
22
|
-
|
|
23
|
-
Shows advanced features and configurations:
|
|
24
|
-
|
|
25
|
-
- Custom client configuration with all options
|
|
26
|
-
- Platform detection and ID extraction
|
|
27
|
-
- Cache management and statistics
|
|
28
|
-
- Unified fetch API for both single and batch operations
|
|
29
|
-
- Error handling and recovery strategies
|
|
30
|
-
- Performance optimization techniques
|
|
31
|
-
|
|
32
|
-
```bash
|
|
33
|
-
node examples/advanced-usage.js
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
### Advanced Features (`advanced-features-example.js`)
|
|
37
|
-
|
|
38
|
-
Comprehensive demonstration of enterprise-grade features:
|
|
39
|
-
|
|
40
|
-
- Rate limiting with all three strategies (token bucket, sliding window, leaky bucket)
|
|
41
|
-
- Comprehensive metrics collection and analysis
|
|
42
|
-
- Plugin system with hooks, middleware, and transformers
|
|
43
|
-
- Error handling with plugins
|
|
44
|
-
- Performance monitoring and optimization
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
node examples/advanced-features-example.js
|
|
48
|
-
```
|
|
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
|
-
|
|
63
|
-
### User-Agent Example (`user-agent-example.js`)
|
|
64
|
-
|
|
65
|
-
Shows how to work with User-Agent headers and custom configurations:
|
|
66
|
-
|
|
67
|
-
- Default User-Agent generation
|
|
68
|
-
- Custom header overrides
|
|
69
|
-
- Platform and version information
|
|
70
|
-
- Browser-like User-Agent strings
|
|
71
|
-
|
|
72
|
-
```bash
|
|
73
|
-
node examples/user-agent-example.js
|
|
74
|
-
```
|
|
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
|
-
|
|
102
|
-
## Key Features Demonstrated
|
|
103
|
-
|
|
104
|
-
### Unified Fetch API
|
|
105
|
-
|
|
106
|
-
The `fetch()` method supports both single URLs and arrays of URLs with comprehensive options:
|
|
107
|
-
|
|
108
|
-
```js
|
|
109
|
-
// Single fetch
|
|
110
|
-
const song = await odesli.fetch('https://open.spotify.com/track/123');
|
|
111
|
-
|
|
112
|
-
// Batch fetch
|
|
113
|
-
const songs = await odesli.fetch([
|
|
114
|
-
'https://open.spotify.com/track/123',
|
|
115
|
-
'https://open.spotify.com/track/456',
|
|
116
|
-
]);
|
|
117
|
-
|
|
118
|
-
// Batch fetch with advanced options
|
|
119
|
-
const songs = await odesli.fetch(urls, {
|
|
120
|
-
country: 'GB',
|
|
121
|
-
concurrency: 3,
|
|
122
|
-
skipCache: true,
|
|
123
|
-
timeout: 5000,
|
|
124
|
-
});
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### Rate Limiting
|
|
128
|
-
|
|
129
|
-
Built-in rate limiting with three strategies and auto-queue functionality:
|
|
130
|
-
|
|
131
|
-
```js
|
|
132
|
-
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
133
|
-
|
|
134
|
-
// Sliding Window (recommended for API compliance)
|
|
135
|
-
const limiter = new RateLimiter({
|
|
136
|
-
maxRequests: 8, // Stay under the 10/minute API limit
|
|
137
|
-
windowMs: 60000, // 1 minute
|
|
138
|
-
strategy: 'sliding-window',
|
|
139
|
-
});
|
|
140
|
-
|
|
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);
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### Metrics Collection
|
|
153
|
-
|
|
154
|
-
Comprehensive metrics tracking with real-time analysis:
|
|
155
|
-
|
|
156
|
-
```js
|
|
157
|
-
const { MetricsCollector } = require('odesli.js/metrics');
|
|
158
|
-
|
|
159
|
-
const metrics = new MetricsCollector({
|
|
160
|
-
enabled: true,
|
|
161
|
-
retentionMs: 24 * 60 * 60 * 1000, // 24 hours
|
|
162
|
-
maxDataPoints: 10000,
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
// Record request with full context
|
|
166
|
-
metrics.recordRequest({
|
|
167
|
-
url: 'https://api.song.link/v1-alpha.1/links',
|
|
168
|
-
method: 'GET',
|
|
169
|
-
startTime: Date.now(),
|
|
170
|
-
endTime: Date.now() + 150,
|
|
171
|
-
success: true,
|
|
172
|
-
statusCode: 200,
|
|
173
|
-
responseTime: 150,
|
|
174
|
-
platform: 'spotify',
|
|
175
|
-
country: 'US',
|
|
176
|
-
cacheHit: false,
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
// Get comprehensive summary
|
|
180
|
-
const summary = metrics.getSummary();
|
|
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');
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
### Plugin System
|
|
193
|
-
|
|
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
|
-
});
|
|
215
|
-
|
|
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
|
-
});
|
|
224
|
-
|
|
225
|
-
// Execute hooks and middleware
|
|
226
|
-
await plugins.executeHook('beforeRequest', {
|
|
227
|
-
url: 'https://api.song.link/test',
|
|
228
|
-
});
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
### Error Handling
|
|
232
|
-
|
|
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
|
-
}
|
|
243
|
-
|
|
244
|
-
// Batch requests with graceful error handling
|
|
245
|
-
const results = await odesli.fetch(urls);
|
|
246
|
-
results.forEach((result, index) => {
|
|
247
|
-
if (result.error) {
|
|
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}`);
|
|
252
|
-
} else {
|
|
253
|
-
console.log(`Song ${index + 1}: ${result.title}`);
|
|
254
|
-
}
|
|
255
|
-
});
|
|
256
|
-
```
|
|
257
|
-
|
|
258
|
-
### Platform Detection and Utilities
|
|
259
|
-
|
|
260
|
-
Utility methods for working with URLs and platforms:
|
|
261
|
-
|
|
262
|
-
```js
|
|
263
|
-
// Detect platform from URL
|
|
264
|
-
const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
|
|
265
|
-
console.log('Platform:', platform); // 'spotify'
|
|
266
|
-
|
|
267
|
-
// Extract ID from URL
|
|
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);
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
## Advanced Features
|
|
281
|
-
|
|
282
|
-
### Rate Limiting Strategies
|
|
283
|
-
|
|
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
|
-
```
|
|
315
|
-
|
|
316
|
-
### Metrics Analysis
|
|
317
|
-
|
|
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
|
|
321
|
-
- **Platform analysis**: Usage by platform and country
|
|
322
|
-
- **Error tracking**: Error patterns, frequency, and suggestions
|
|
323
|
-
- **Rate limit monitoring**: Rate limit hits and average delays
|
|
324
|
-
|
|
325
|
-
### Plugin System Features
|
|
326
|
-
|
|
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
|
|
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
|
|
333
|
-
|
|
334
|
-
## Running Examples
|
|
335
|
-
|
|
336
|
-
### Prerequisites
|
|
337
|
-
|
|
338
|
-
```bash
|
|
339
|
-
npm install
|
|
340
|
-
```
|
|
341
|
-
|
|
342
|
-
### Basic Examples
|
|
343
|
-
|
|
344
|
-
```bash
|
|
345
|
-
# Basic usage
|
|
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
|
|
363
|
-
```
|
|
364
|
-
|
|
365
|
-
### Environment Variables
|
|
366
|
-
|
|
367
|
-
Some examples use environment variables for API keys:
|
|
368
|
-
|
|
369
|
-
```bash
|
|
370
|
-
# Optional: Set API key for higher rate limits
|
|
371
|
-
export ODESLI_API_KEY=your-api-key-here
|
|
372
|
-
|
|
373
|
-
# Run examples with API key
|
|
374
|
-
node examples/advanced-features-example.js
|
|
375
|
-
```
|
|
376
|
-
|
|
377
|
-
### Testing
|
|
378
|
-
|
|
379
|
-
Run the comprehensive test suite:
|
|
380
|
-
|
|
381
|
-
```bash
|
|
382
|
-
npm test
|
|
383
|
-
npm test -- --testNamePattern="Advanced Features"
|
|
384
|
-
```
|
|
385
|
-
|
|
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
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
// Advanced Features Example for Odesli.js
|
|
2
|
-
// This example demonstrates the use of extensions: Rate Limiter, Metrics Collector, and Plugin System.
|
|
3
|
-
//
|
|
4
|
-
// - Rate Limiter: Prevents hitting API rate limits and smooths out traffic spikes.
|
|
5
|
-
// - Metrics Collector: Tracks requests, errors, and performance for analytics and debugging.
|
|
6
|
-
// - Plugin System: Lets you add hooks, middleware, and transformers for custom logic (logging, analytics, etc).
|
|
7
|
-
|
|
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
|
-
|
|
13
|
-
async function advancedExample() {
|
|
14
|
-
console.log('=== Advanced Features Example ===\n');
|
|
15
|
-
|
|
16
|
-
// 1. Rate Limiting
|
|
17
|
-
// Controls the number of API requests per time window.
|
|
18
|
-
// Prevents hitting Odesli/Songlink API rate limits and smooths out spikes.
|
|
19
|
-
console.log('1. Rate Limiting Setup...');
|
|
20
|
-
const rateLimiter = new RateLimiter({
|
|
21
|
-
maxRequests: 10,
|
|
22
|
-
windowMs: 60000, // 1 minute
|
|
23
|
-
strategy: 'token-bucket',
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
// 2. Metrics Collection
|
|
27
|
-
// Tracks requests, errors, cache hits, and response times for analytics and debugging.
|
|
28
|
-
console.log('2. Metrics Collection Setup...');
|
|
29
|
-
const metrics = new MetricsCollector({
|
|
30
|
-
enabled: true,
|
|
31
|
-
retentionMs: 3600000, // 1 hour
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
// 3. Plugin System
|
|
35
|
-
// Lets you add hooks, middleware, and transformers for custom logic (logging, analytics, etc).
|
|
36
|
-
console.log('3. Plugin System Setup...');
|
|
37
|
-
const pluginSystem = new PluginSystem();
|
|
38
|
-
|
|
39
|
-
// Register a logging plugin to log requests and responses
|
|
40
|
-
pluginSystem.registerPlugin('logging', {
|
|
41
|
-
name: 'logging',
|
|
42
|
-
description: 'Logs all requests and responses',
|
|
43
|
-
hooks: {
|
|
44
|
-
'pre-request': context => {
|
|
45
|
-
console.log(`🔄 Making request to: ${context.url}`);
|
|
46
|
-
},
|
|
47
|
-
'post-response': context => {
|
|
48
|
-
console.log(`✅ Response received for: ${context.url}`);
|
|
49
|
-
},
|
|
50
|
-
},
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
// Register an analytics plugin to track request analytics
|
|
54
|
-
pluginSystem.registerPlugin('analytics', {
|
|
55
|
-
name: 'analytics',
|
|
56
|
-
description: 'Tracks request analytics',
|
|
57
|
-
hooks: {
|
|
58
|
-
'post-response': context => {
|
|
59
|
-
metrics.recordRequest({
|
|
60
|
-
url: context.url,
|
|
61
|
-
startTime: context.startTime,
|
|
62
|
-
endTime: Date.now(),
|
|
63
|
-
success: true,
|
|
64
|
-
responseTime: Date.now() - context.startTime,
|
|
65
|
-
});
|
|
66
|
-
},
|
|
67
|
-
},
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
// 4. Initialize Odesli with advanced features
|
|
71
|
-
// You can pass a logger function for custom logging.
|
|
72
|
-
const odesli = new Odesli({
|
|
73
|
-
timeout: 15000,
|
|
74
|
-
maxRetries: 3,
|
|
75
|
-
retryDelay: 2000,
|
|
76
|
-
cache: true,
|
|
77
|
-
logger: (message, level) => {
|
|
78
|
-
console.log(`[${level.toUpperCase()}] ${message}`);
|
|
79
|
-
},
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
try {
|
|
83
|
-
// 5. Execute hooks before requests (for logging, analytics, etc)
|
|
84
|
-
await pluginSystem.executeHook('pre-request', {
|
|
85
|
-
url: 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
86
|
-
startTime: Date.now(),
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
// 6. Wait for rate limiter slot (prevents exceeding API limits)
|
|
90
|
-
await rateLimiter.waitForSlot();
|
|
91
|
-
|
|
92
|
-
// 7. Make request with advanced options
|
|
93
|
-
console.log('\n4. Making request with advanced features...');
|
|
94
|
-
const song = await odesli.fetch(
|
|
95
|
-
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
96
|
-
{
|
|
97
|
-
country: 'US',
|
|
98
|
-
skipCache: false,
|
|
99
|
-
timeout: 10000,
|
|
100
|
-
}
|
|
101
|
-
);
|
|
102
|
-
|
|
103
|
-
// 8. Execute hooks after response (for logging, analytics, etc)
|
|
104
|
-
await pluginSystem.executeHook('post-response', {
|
|
105
|
-
url: 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
106
|
-
startTime: Date.now() - 1000,
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
console.log(`Title: ${song.title}`);
|
|
110
|
-
console.log(`Artist: ${song.artist.join(', ')}`);
|
|
111
|
-
|
|
112
|
-
// 9. Show metrics summary (API usage, performance, etc)
|
|
113
|
-
console.log('\n5. Metrics Summary:');
|
|
114
|
-
const summary = metrics.getSummary();
|
|
115
|
-
console.log(`Total Requests: ${summary.counters.totalRequests}`);
|
|
116
|
-
console.log(
|
|
117
|
-
`Success Rate: ${(summary.rates.successRate * 100).toFixed(1)}%`
|
|
118
|
-
);
|
|
119
|
-
console.log(
|
|
120
|
-
`Average Response Time: ${summary.recent.avgResponseTime.toFixed(0)}ms`
|
|
121
|
-
);
|
|
122
|
-
|
|
123
|
-
// 10. Show rate limiter status
|
|
124
|
-
console.log('\n6. Rate Limiter Status:');
|
|
125
|
-
const rateStatus = rateLimiter.getStatus();
|
|
126
|
-
console.log(`Available slots: ${rateStatus.available}/${rateStatus.max}`);
|
|
127
|
-
console.log(`Used in window: ${rateStatus.used}`);
|
|
128
|
-
|
|
129
|
-
// 11. Show plugin information
|
|
130
|
-
console.log('\n7. Active Plugins:');
|
|
131
|
-
const plugins = pluginSystem.getPlugins();
|
|
132
|
-
plugins.forEach(pluginName => {
|
|
133
|
-
const info = pluginSystem.getPluginInfo(pluginName);
|
|
134
|
-
console.log(`- ${info.name}: ${info.description}`);
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
// 12. Demonstrate country options
|
|
138
|
-
console.log('\n8. Country Options:');
|
|
139
|
-
const countryOptions = Odesli.getCountryOptions();
|
|
140
|
-
console.log(`Available countries: ${countryOptions.length}`);
|
|
141
|
-
const popularCountries = countryOptions.filter(c =>
|
|
142
|
-
['US', 'GB', 'CA', 'AU', 'DE', 'FR', 'JP'].includes(c.code)
|
|
143
|
-
);
|
|
144
|
-
console.log('Popular countries:');
|
|
145
|
-
popularCountries.forEach(c => {
|
|
146
|
-
console.log(` ${c.code}: ${c.name}`);
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
// 13. Demonstrate batch fetching with rate limiting
|
|
150
|
-
console.log('\n9. Batch fetching with rate limiting...');
|
|
151
|
-
const urls = [
|
|
152
|
-
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
153
|
-
'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900',
|
|
154
|
-
];
|
|
155
|
-
|
|
156
|
-
const batchResults = [];
|
|
157
|
-
for (const url of urls) {
|
|
158
|
-
await rateLimiter.waitForSlot();
|
|
159
|
-
await pluginSystem.executeHook('pre-request', {
|
|
160
|
-
url,
|
|
161
|
-
startTime: Date.now(),
|
|
162
|
-
});
|
|
163
|
-
|
|
164
|
-
try {
|
|
165
|
-
const result = await odesli.fetch(url, { country: 'US' });
|
|
166
|
-
batchResults.push(result);
|
|
167
|
-
await pluginSystem.executeHook('post-response', {
|
|
168
|
-
url,
|
|
169
|
-
startTime: Date.now() - 1000,
|
|
170
|
-
});
|
|
171
|
-
console.log(`✅ ${result.title}`);
|
|
172
|
-
} catch (error) {
|
|
173
|
-
console.log(`❌ Error: ${error.message}`);
|
|
174
|
-
metrics.recordError(error, { url });
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
console.log(
|
|
179
|
-
`Batch completed: ${batchResults.length}/${urls.length} successful`
|
|
180
|
-
);
|
|
181
|
-
} catch (error) {
|
|
182
|
-
if (
|
|
183
|
-
error.message &&
|
|
184
|
-
(error.message.includes('401') || error.message.includes('429'))
|
|
185
|
-
) {
|
|
186
|
-
console.error('Error:', error.message);
|
|
187
|
-
console.error(
|
|
188
|
-
'You may need an API key for higher limits. See https://odesli.co/'
|
|
189
|
-
);
|
|
190
|
-
} else {
|
|
191
|
-
console.error('Error:', error.message);
|
|
192
|
-
}
|
|
193
|
-
// Record error in metrics
|
|
194
|
-
metrics.recordError(error, {
|
|
195
|
-
url: 'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// 14. Cleanup
|
|
200
|
-
console.log('\n10. Cleaning up...');
|
|
201
|
-
metrics.cleanup();
|
|
202
|
-
console.log('✅ Advanced features example completed!');
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
advancedExample();
|