odesli.js 1.3.5 ā 1.3.7
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/.prettierignore +30 -30
- package/API_IMPROVEMENTS.md +16 -16
- package/CHANGELOG.md +106 -0
- package/LICENSE +14 -14
- package/README.md +467 -91
- 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/index.d.ts +391 -363
- package/lib/rate-limiter.js +16 -15
- package/package.json +13 -1
package/README.md
CHANGED
|
@@ -16,15 +16,12 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
|
|
|
16
16
|
- [š Table of Contents](#-table-of-contents)
|
|
17
17
|
- [Features](#features)
|
|
18
18
|
- [Installation](#installation)
|
|
19
|
-
- [From npm
|
|
20
|
-
- [From GitHub Packages](#from-github-packages)
|
|
19
|
+
- [From npm](#from-npm)
|
|
21
20
|
- [Quick Start](#quick-start)
|
|
22
21
|
- [API Key](#api-key)
|
|
23
22
|
- [Usage](#usage)
|
|
24
23
|
- [Basic Usage](#basic-usage)
|
|
25
24
|
- [Advanced Usage](#advanced-usage)
|
|
26
|
-
- [ESM (import)](#esm-import)
|
|
27
|
-
- [CommonJS (require)](#commonjs-require)
|
|
28
25
|
- [Response Format](#response-format)
|
|
29
26
|
- [Supported Platforms](#supported-platforms)
|
|
30
27
|
- [TypeScript Support](#typescript-support)
|
|
@@ -36,6 +33,8 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
|
|
|
36
33
|
- [Support](#support)
|
|
37
34
|
- [Extensions: Advanced Features](#extensions-advanced-features)
|
|
38
35
|
- [1. Rate Limiter](#1-rate-limiter)
|
|
36
|
+
- [Example: With vs Without RateLimiter](#example-with-vs-without-ratelimiter)
|
|
37
|
+
- [Example: Using RateLimiter with Multiple Fetches](#example-using-ratelimiter-with-multiple-fetches)
|
|
39
38
|
- [2. Metrics Collector](#2-metrics-collector)
|
|
40
39
|
- [3. Plugin System](#3-plugin-system)
|
|
41
40
|
|
|
@@ -52,36 +51,72 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
|
|
|
52
51
|
|
|
53
52
|
## Installation
|
|
54
53
|
|
|
55
|
-
### From npm
|
|
54
|
+
### From npm
|
|
56
55
|
|
|
57
56
|
```bash
|
|
58
57
|
npm install odesli.js
|
|
59
58
|
```
|
|
60
59
|
|
|
61
|
-
|
|
60
|
+
## Quick Start
|
|
62
61
|
|
|
63
|
-
|
|
64
|
-
npm install @mattraus/odesli.js
|
|
65
|
-
```
|
|
62
|
+
**CommonJS (require):**
|
|
66
63
|
|
|
67
|
-
|
|
64
|
+
```js
|
|
65
|
+
const Odesli = require('odesli.js');
|
|
68
66
|
|
|
69
|
-
|
|
67
|
+
// Initialize without API key (10 requests/minute limit)
|
|
68
|
+
const odesli = new Odesli();
|
|
70
69
|
|
|
71
|
-
|
|
72
|
-
const
|
|
70
|
+
// Or with API key for higher limits
|
|
71
|
+
// const odesli = new Odesli({
|
|
72
|
+
// apiKey: 'your-api-key-here',
|
|
73
|
+
// version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
|
|
74
|
+
// });
|
|
75
|
+
|
|
76
|
+
// You can also disable the metrics collector if you don't need it
|
|
77
|
+
// const odesliLight = new Odesli({ metrics: false });
|
|
78
|
+
|
|
79
|
+
// Fetch a song by URL (this is the actual working example)
|
|
80
|
+
(async () => {
|
|
81
|
+
try {
|
|
82
|
+
const song = await odesli.fetch(
|
|
83
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
84
|
+
);
|
|
85
|
+
console.log(`šµ ${song.title} by ${song.artist.join(', ')}`);
|
|
86
|
+
console.log(`š Song.link: ${song.pageUrl}`);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error('ā Error:', error.message);
|
|
89
|
+
}
|
|
90
|
+
})();
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**ESM (import):**
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
import Odesli from 'odesli.js';
|
|
73
97
|
|
|
74
98
|
// Initialize without API key (10 requests/minute limit)
|
|
75
99
|
const odesli = new Odesli();
|
|
76
100
|
|
|
77
101
|
// Or with API key for higher limits
|
|
78
|
-
const odesli = new Odesli({
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
});
|
|
102
|
+
// const odesli = new Odesli({
|
|
103
|
+
// apiKey: 'your-api-key-here',
|
|
104
|
+
// version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
|
|
105
|
+
// });
|
|
82
106
|
|
|
83
107
|
// You can also disable the metrics collector if you don't need it
|
|
84
|
-
const odesliLight = new Odesli({ metrics: false });
|
|
108
|
+
// const odesliLight = new Odesli({ metrics: false });
|
|
109
|
+
|
|
110
|
+
// Fetch a song by URL (this is the actual working example)
|
|
111
|
+
try {
|
|
112
|
+
const song = await odesli.fetch(
|
|
113
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
114
|
+
);
|
|
115
|
+
console.log(`šµ ${song.title} by ${song.artist.join(', ')}`);
|
|
116
|
+
console.log(`š Song.link: ${song.pageUrl}`);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
console.error('ā Error:', error.message);
|
|
119
|
+
}
|
|
85
120
|
```
|
|
86
121
|
|
|
87
122
|
## API Key
|
|
@@ -94,16 +129,48 @@ To get an API key, email `developers@song.link`.
|
|
|
94
129
|
|
|
95
130
|
### Basic Usage
|
|
96
131
|
|
|
97
|
-
|
|
132
|
+
**CommonJS (require):**
|
|
133
|
+
|
|
134
|
+
```js
|
|
98
135
|
const Odesli = require('odesli.js');
|
|
99
136
|
|
|
100
137
|
// Initialize without API key (10 requests/minute limit)
|
|
101
138
|
const odesli = new Odesli();
|
|
102
139
|
|
|
103
140
|
// Or with API key for higher limits
|
|
104
|
-
const odesli = new Odesli({
|
|
105
|
-
|
|
106
|
-
});
|
|
141
|
+
// const odesli = new Odesli({
|
|
142
|
+
// apiKey: 'your-api-key-here',
|
|
143
|
+
// });
|
|
144
|
+
|
|
145
|
+
(async () => {
|
|
146
|
+
// Fetch a song by URL
|
|
147
|
+
const song = await odesli.fetch(
|
|
148
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
149
|
+
);
|
|
150
|
+
console.log(`${song.title} by ${song.artist.join(', ')}`);
|
|
151
|
+
|
|
152
|
+
// Fetch multiple songs at once
|
|
153
|
+
const urls = [
|
|
154
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
155
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
156
|
+
];
|
|
157
|
+
const songs = await odesli.fetch(urls);
|
|
158
|
+
songs.forEach(song => console.log(song.title));
|
|
159
|
+
})();
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
**ESM (import):**
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
import Odesli from 'odesli.js';
|
|
166
|
+
|
|
167
|
+
// Initialize without API key (10 requests/minute limit)
|
|
168
|
+
const odesli = new Odesli();
|
|
169
|
+
|
|
170
|
+
// Or with API key for higher limits
|
|
171
|
+
// const odesli = new Odesli({
|
|
172
|
+
// apiKey: 'your-api-key-here',
|
|
173
|
+
// });
|
|
107
174
|
|
|
108
175
|
// Fetch a song by URL
|
|
109
176
|
const song = await odesli.fetch(
|
|
@@ -122,7 +189,11 @@ songs.forEach(song => console.log(song.title));
|
|
|
122
189
|
|
|
123
190
|
### Advanced Usage
|
|
124
191
|
|
|
125
|
-
|
|
192
|
+
**CommonJS (require):**
|
|
193
|
+
|
|
194
|
+
```js
|
|
195
|
+
const Odesli = require('odesli.js');
|
|
196
|
+
|
|
126
197
|
// Initialize with custom options
|
|
127
198
|
const odesli = new Odesli({
|
|
128
199
|
apiKey: 'your-api-key-here',
|
|
@@ -136,18 +207,71 @@ const odesli = new Odesli({
|
|
|
136
207
|
logger: (message, level) => console.log(`[${level}] ${message}`),
|
|
137
208
|
});
|
|
138
209
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
210
|
+
(async () => {
|
|
211
|
+
// Fetch with options
|
|
212
|
+
const song = await odesli.fetch('https://open.spotify.com/track/123', {
|
|
213
|
+
country: 'GB',
|
|
214
|
+
skipCache: false,
|
|
215
|
+
timeout: 5000,
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// Batch fetch with concurrency control
|
|
219
|
+
const urls = [
|
|
220
|
+
'https://open.spotify.com/track/123',
|
|
221
|
+
'https://music.apple.com/us/album/test/456?i=789',
|
|
222
|
+
'https://www.youtube.com/watch?v=abc123',
|
|
223
|
+
];
|
|
224
|
+
|
|
225
|
+
const songs = await odesli.fetch(urls, {
|
|
226
|
+
country: 'US',
|
|
227
|
+
concurrency: 3,
|
|
228
|
+
skipCache: true,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// Handle errors in batch results
|
|
232
|
+
songs.forEach((song, index) => {
|
|
233
|
+
if (song.error) {
|
|
234
|
+
console.log(`Song ${index + 1}: Error - ${song.error}`);
|
|
235
|
+
} else {
|
|
236
|
+
console.log(`Song ${index + 1}: ${song.title}`);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
})();
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**ESM (import):**
|
|
243
|
+
|
|
244
|
+
```js
|
|
245
|
+
import Odesli from 'odesli.js';
|
|
246
|
+
|
|
247
|
+
// Initialize with custom options
|
|
248
|
+
const odesli = new Odesli({
|
|
249
|
+
apiKey: 'your-api-key-here',
|
|
250
|
+
version: 'v1-alpha.1',
|
|
251
|
+
cache: true,
|
|
252
|
+
timeout: 10000,
|
|
253
|
+
maxRetries: 3,
|
|
254
|
+
retryDelay: 1000,
|
|
255
|
+
headers: { 'User-Agent': 'MyApp/1.0' },
|
|
256
|
+
validateParams: true,
|
|
257
|
+
logger: (message, level) => console.log(`[${level}] ${message}`),
|
|
144
258
|
});
|
|
145
259
|
|
|
260
|
+
// Fetch with options
|
|
261
|
+
const song = await odesli.fetch(
|
|
262
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
263
|
+
{
|
|
264
|
+
country: 'GB',
|
|
265
|
+
skipCache: false,
|
|
266
|
+
timeout: 5000,
|
|
267
|
+
}
|
|
268
|
+
);
|
|
269
|
+
|
|
146
270
|
// Batch fetch with concurrency control
|
|
147
271
|
const urls = [
|
|
148
|
-
'https://open.spotify.com/track/
|
|
149
|
-
'https://
|
|
150
|
-
'https://
|
|
272
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
273
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
274
|
+
'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
|
|
151
275
|
];
|
|
152
276
|
|
|
153
277
|
const songs = await odesli.fetch(urls, {
|
|
@@ -166,29 +290,11 @@ songs.forEach((song, index) => {
|
|
|
166
290
|
});
|
|
167
291
|
```
|
|
168
292
|
|
|
169
|
-
### ESM (import)
|
|
170
|
-
|
|
171
|
-
```js
|
|
172
|
-
import { Odesli } from '@mattraus/odesli.js';
|
|
173
|
-
import { RateLimiter } from '@mattraus/odesli.js/rate-limiter';
|
|
174
|
-
import { MetricsCollector } from '@mattraus/odesli.js/metrics';
|
|
175
|
-
import { PluginSystem } from '@mattraus/odesli.js/plugin-system';
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
### CommonJS (require)
|
|
179
|
-
|
|
180
|
-
```js
|
|
181
|
-
const { Odesli } = require('@mattraus/odesli.js');
|
|
182
|
-
const { RateLimiter } = require('@mattraus/odesli.js/rate-limiter');
|
|
183
|
-
const { MetricsCollector } = require('@mattraus/odesli.js/metrics');
|
|
184
|
-
const { PluginSystem } = require('@mattraus/odesli.js/plugin-system');
|
|
185
|
-
```
|
|
186
|
-
|
|
187
293
|
## Response Format
|
|
188
294
|
|
|
189
295
|
All methods return a response object with the following structure:
|
|
190
296
|
|
|
191
|
-
```
|
|
297
|
+
```js
|
|
192
298
|
{
|
|
193
299
|
entityUniqueId: "SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR",
|
|
194
300
|
title: "Bad and Boujee",
|
|
@@ -245,20 +351,60 @@ All methods return a response object with the following structure:
|
|
|
245
351
|
|
|
246
352
|
This package includes full TypeScript definitions with strict country code validation:
|
|
247
353
|
|
|
354
|
+
**CommonJS (require):**
|
|
355
|
+
|
|
248
356
|
```typescript
|
|
249
|
-
|
|
357
|
+
const Odesli = require('odesli.js');
|
|
250
358
|
|
|
251
359
|
const odesli = new Odesli({ apiKey: 'your-key' });
|
|
252
360
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
361
|
+
(async () => {
|
|
362
|
+
// Get all valid country codes and names for UI dropdowns
|
|
363
|
+
const countryOptions = Odesli.getCountryOptions();
|
|
364
|
+
console.log('Top 3 countries:', countryOptions.slice(0, 3));
|
|
365
|
+
// Output: [
|
|
366
|
+
// { code: 'US', name: 'United States' },
|
|
367
|
+
// { code: 'GB', name: 'United Kingdom' },
|
|
368
|
+
// { code: 'CA', name: 'Canada' }
|
|
369
|
+
// ]
|
|
370
|
+
|
|
371
|
+
// TypeScript enforces valid country codes
|
|
372
|
+
const song = await odesli.fetch(
|
|
373
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
374
|
+
{
|
|
375
|
+
country: 'US', // ā
Valid - TypeScript autocomplete shows all valid codes
|
|
376
|
+
// country: 'INVALID' // ā TypeScript error - not a valid CountryCode
|
|
377
|
+
}
|
|
378
|
+
);
|
|
379
|
+
console.log(`Fetched: ${song.title}`);
|
|
380
|
+
})();
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
**ESM (import):**
|
|
384
|
+
|
|
385
|
+
```typescript
|
|
386
|
+
import Odesli, { CountryCode } from 'odesli.js';
|
|
387
|
+
|
|
388
|
+
const odesli = new Odesli({ apiKey: 'your-key' });
|
|
258
389
|
|
|
259
390
|
// Get all valid country codes and names for UI dropdowns
|
|
260
391
|
const countryOptions = Odesli.getCountryOptions();
|
|
261
|
-
|
|
392
|
+
console.log('Top 3 countries:', countryOptions.slice(0, 3));
|
|
393
|
+
// Output: [
|
|
394
|
+
// { code: 'US', name: 'United States' },
|
|
395
|
+
// { code: 'GB', name: 'United Kingdom' },
|
|
396
|
+
// { code: 'CA', name: 'Canada' }
|
|
397
|
+
// ]
|
|
398
|
+
|
|
399
|
+
// TypeScript enforces valid country codes
|
|
400
|
+
const song = await odesli.fetch(
|
|
401
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
402
|
+
{
|
|
403
|
+
country: 'US', // ā
Valid - TypeScript autocomplete shows all valid codes
|
|
404
|
+
// country: 'INVALID' // ā TypeScript error - not a valid CountryCode
|
|
405
|
+
}
|
|
406
|
+
);
|
|
407
|
+
console.log(`Fetched: ${song.title}`);
|
|
262
408
|
```
|
|
263
409
|
|
|
264
410
|
## Examples
|
|
@@ -273,23 +419,87 @@ Check out the [examples directory](./examples) for comprehensive usage examples:
|
|
|
273
419
|
|
|
274
420
|
**Country-specific fetching:**
|
|
275
421
|
|
|
276
|
-
|
|
422
|
+
**CommonJS (require):**
|
|
423
|
+
|
|
424
|
+
```js
|
|
425
|
+
const Odesli = require('odesli.js');
|
|
426
|
+
|
|
427
|
+
const odesli = new Odesli();
|
|
428
|
+
|
|
429
|
+
// Get country options for UI dropdowns
|
|
430
|
+
const countries = Odesli.getCountryOptions();
|
|
431
|
+
console.log(`Available countries: ${countries.length}`);
|
|
432
|
+
|
|
433
|
+
(async () => {
|
|
434
|
+
// Fetch with specific country
|
|
435
|
+
const song = await odesli.fetch(
|
|
436
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
437
|
+
{
|
|
438
|
+
country: 'GB', // United Kingdom
|
|
439
|
+
}
|
|
440
|
+
);
|
|
441
|
+
console.log(`Fetched: ${song.title}`);
|
|
442
|
+
})();
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
**ESM (import):**
|
|
446
|
+
|
|
447
|
+
```js
|
|
448
|
+
import Odesli from 'odesli.js';
|
|
449
|
+
|
|
450
|
+
const odesli = new Odesli();
|
|
451
|
+
|
|
277
452
|
// Get country options for UI dropdowns
|
|
278
453
|
const countries = Odesli.getCountryOptions();
|
|
279
454
|
console.log(`Available countries: ${countries.length}`);
|
|
280
455
|
|
|
281
456
|
// Fetch with specific country
|
|
282
|
-
const song = await odesli.fetch(
|
|
283
|
-
|
|
284
|
-
|
|
457
|
+
const song = await odesli.fetch(
|
|
458
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
459
|
+
{
|
|
460
|
+
country: 'GB', // United Kingdom
|
|
461
|
+
}
|
|
462
|
+
);
|
|
463
|
+
console.log(`Fetched: ${song.title}`);
|
|
285
464
|
```
|
|
286
465
|
|
|
287
466
|
**Batch fetching with error handling:**
|
|
288
467
|
|
|
289
|
-
|
|
468
|
+
**CommonJS (require):**
|
|
469
|
+
|
|
470
|
+
```js
|
|
471
|
+
const Odesli = require('odesli.js');
|
|
472
|
+
|
|
473
|
+
const odesli = new Odesli();
|
|
474
|
+
|
|
475
|
+
const urls = [
|
|
476
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
477
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
478
|
+
];
|
|
479
|
+
|
|
480
|
+
(async () => {
|
|
481
|
+
const results = await odesli.fetch(urls, { country: 'US' });
|
|
482
|
+
|
|
483
|
+
results.forEach((result, index) => {
|
|
484
|
+
if (result.error) {
|
|
485
|
+
console.log(`Song ${index + 1}: Error - ${result.error}`);
|
|
486
|
+
} else {
|
|
487
|
+
console.log(`Song ${index + 1}: ${result.title}`);
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
})();
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
**ESM (import):**
|
|
494
|
+
|
|
495
|
+
```js
|
|
496
|
+
import Odesli from 'odesli.js';
|
|
497
|
+
|
|
498
|
+
const odesli = new Odesli();
|
|
499
|
+
|
|
290
500
|
const urls = [
|
|
291
|
-
'https://open.spotify.com/track/
|
|
292
|
-
'https://
|
|
501
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
502
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
293
503
|
];
|
|
294
504
|
|
|
295
505
|
const results = await odesli.fetch(urls, { country: 'US' });
|
|
@@ -305,9 +515,37 @@ results.forEach((result, index) => {
|
|
|
305
515
|
|
|
306
516
|
**Platform detection and ID extraction:**
|
|
307
517
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
518
|
+
**CommonJS (require):**
|
|
519
|
+
|
|
520
|
+
```js
|
|
521
|
+
const Odesli = require('odesli.js');
|
|
522
|
+
|
|
523
|
+
const odesli = new Odesli();
|
|
524
|
+
|
|
525
|
+
// These methods are synchronous, so no async handling needed
|
|
526
|
+
const platform = odesli.detectPlatform(
|
|
527
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
528
|
+
);
|
|
529
|
+
const id = odesli.extractId(
|
|
530
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
531
|
+
);
|
|
532
|
+
console.log(`Platform: ${platform}, ID: ${id}`);
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
**ESM (import):**
|
|
536
|
+
|
|
537
|
+
```js
|
|
538
|
+
import Odesli from 'odesli.js';
|
|
539
|
+
|
|
540
|
+
const odesli = new Odesli();
|
|
541
|
+
|
|
542
|
+
// These methods are synchronous, so no async handling needed
|
|
543
|
+
const platform = odesli.detectPlatform(
|
|
544
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
545
|
+
);
|
|
546
|
+
const id = odesli.extractId(
|
|
547
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
548
|
+
);
|
|
311
549
|
console.log(`Platform: ${platform}, ID: ${id}`);
|
|
312
550
|
```
|
|
313
551
|
|
|
@@ -341,18 +579,155 @@ Odesli.js provides several advanced extensions to help you build robust, scalabl
|
|
|
341
579
|
|
|
342
580
|
**What:** Controls the number of API requests per time window using strategies like token bucket, leaky bucket, or sliding window.
|
|
343
581
|
|
|
344
|
-
**
|
|
582
|
+
**Default Rate Limiting Behavior:**
|
|
583
|
+
|
|
584
|
+
The main Odesli client does **not** include built-in rate limiting. Rate limits are enforced by the Odesli API server:
|
|
585
|
+
|
|
586
|
+
- **Without API key**: 10 requests per minute (enforced by API)
|
|
587
|
+
- **With API key**: Higher limits (enforced by API)
|
|
588
|
+
|
|
589
|
+
When you exceed the API rate limit, you'll receive a 429 error: `"You are being rate limited, No API Key is 10 Requests / Minute"`
|
|
590
|
+
|
|
591
|
+
**Why use the RateLimiter extension?**
|
|
592
|
+
|
|
593
|
+
- **Prevent API errors**: Proactively limit requests before hitting API rate limits
|
|
594
|
+
- **Smooth traffic**: Spread requests evenly across time windows
|
|
595
|
+
- **Handle bursts**: Manage sudden spikes in request volume
|
|
596
|
+
- **Better UX**: Avoid 429 errors by staying under limits
|
|
597
|
+
- **Predictable behavior**: Ensure consistent request patterns
|
|
598
|
+
|
|
599
|
+
**Available Strategies:**
|
|
600
|
+
|
|
601
|
+
- **šÆ Token Bucket**: Handles bursts well, efficient memory usage
|
|
602
|
+
- **š Sliding Window**: Most accurate, precise timing (recommended)
|
|
603
|
+
- **š§ Leaky Bucket**: Smooths traffic, predictable output rate
|
|
345
604
|
|
|
346
|
-
|
|
347
|
-
- Smooths out traffic spikes
|
|
348
|
-
- Ensures fair usage in multi-user or batch scenarios
|
|
605
|
+
**Strategy Options:**
|
|
349
606
|
|
|
350
|
-
|
|
607
|
+
```js
|
|
608
|
+
// Token Bucket Strategy
|
|
609
|
+
const tokenBucketLimiter = new RateLimiter({
|
|
610
|
+
maxRequests: 10,
|
|
611
|
+
windowMs: 60000, // 1 minute
|
|
612
|
+
strategy: 'token-bucket',
|
|
613
|
+
// Optional: burst capacity (defaults to maxRequests)
|
|
614
|
+
burstCapacity: 15,
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
// Sliding Window Strategy (recommended)
|
|
618
|
+
const slidingWindowLimiter = new RateLimiter({
|
|
619
|
+
maxRequests: 5,
|
|
620
|
+
windowMs: 10000, // 10 seconds
|
|
621
|
+
strategy: 'sliding-window',
|
|
622
|
+
// No additional options needed
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
// Leaky Bucket Strategy
|
|
626
|
+
const leakyBucketLimiter = new RateLimiter({
|
|
627
|
+
maxRequests: 3,
|
|
628
|
+
windowMs: 5000, // 5 seconds
|
|
629
|
+
strategy: 'leaky-bucket',
|
|
630
|
+
// Optional: queue size limit (defaults to maxRequests * 2)
|
|
631
|
+
queueSize: 10,
|
|
632
|
+
});
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
**Strategy Comparison:**
|
|
636
|
+
|
|
637
|
+
| Strategy | Pros | Cons | Best For | Configuration |
|
|
638
|
+
| ------------------ | -------------------------------- | ------------------- | --------------------------------- | ---------------------- |
|
|
639
|
+
| **Token Bucket** | Handles bursts, efficient memory | Less precise timing | Allowing some burst traffic | `burstCapacity` option |
|
|
640
|
+
| **Sliding Window** | Most accurate, no overages | More memory usage | Exact rate limiting (recommended) | No additional options |
|
|
641
|
+
| **Leaky Bucket** | Smooths traffic, predictable | Can delay requests | Smoothing traffic spikes | `queueSize` option |
|
|
642
|
+
|
|
643
|
+
**When to Use Each Strategy:**
|
|
644
|
+
|
|
645
|
+
- **šÆ Token Bucket**: Use when you want to allow some burst traffic while maintaining overall limits. Good for user-facing applications where occasional bursts are acceptable.
|
|
646
|
+
|
|
647
|
+
- **š Sliding Window**: Use when you need precise rate limiting with no overages. Best for API integrations where you must stay strictly within limits.
|
|
648
|
+
|
|
649
|
+
- **š§ Leaky Bucket**: Use when you want to smooth out traffic spikes and maintain a steady, predictable output rate. Good for background processing or batch operations.
|
|
650
|
+
|
|
651
|
+
#### Example: With vs Without RateLimiter
|
|
652
|
+
|
|
653
|
+
```js
|
|
654
|
+
const Odesli = require('odesli.js');
|
|
655
|
+
|
|
656
|
+
// Without RateLimiter - relies on API rate limiting
|
|
657
|
+
const odesli = new Odesli();
|
|
658
|
+
|
|
659
|
+
// This works fine for < 10 requests/minute
|
|
660
|
+
// But will throw 429 errors if you exceed the limit
|
|
661
|
+
const urls = [
|
|
662
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
663
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
664
|
+
];
|
|
665
|
+
const songs = await odesli.fetch(urls); // May hit API rate limit
|
|
666
|
+
|
|
667
|
+
// With RateLimiter - proactive client-side limiting
|
|
668
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
669
|
+
const limiter = new RateLimiter({
|
|
670
|
+
maxRequests: 8, // Stay safely under the 10/minute limit
|
|
671
|
+
windowMs: 60000,
|
|
672
|
+
strategy: 'sliding-window',
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
// This prevents hitting API rate limits
|
|
676
|
+
async function safeFetch(url) {
|
|
677
|
+
await limiter.waitForSlot();
|
|
678
|
+
return await odesli.fetch(url);
|
|
679
|
+
}
|
|
680
|
+
```
|
|
681
|
+
|
|
682
|
+
#### Example: Using RateLimiter with Multiple Fetches
|
|
683
|
+
|
|
684
|
+
**CommonJS (require):**
|
|
351
685
|
|
|
352
686
|
```js
|
|
353
|
-
const
|
|
354
|
-
const
|
|
355
|
-
|
|
687
|
+
const Odesli = require('odesli.js');
|
|
688
|
+
const { RateLimiter } = require('odesli.js/rate-limiter');
|
|
689
|
+
|
|
690
|
+
const odesli = new Odesli();
|
|
691
|
+
const limiter = new RateLimiter({
|
|
692
|
+
maxRequests: 2,
|
|
693
|
+
windowMs: 3000, // 2 requests per 3 seconds
|
|
694
|
+
strategy: 'sliding-window', // More reliable strategy
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
const urls = [
|
|
698
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
699
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
700
|
+
'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
|
|
701
|
+
];
|
|
702
|
+
|
|
703
|
+
// Function to fetch with rate limiting
|
|
704
|
+
async function fetchWithRateLimit(url, index) {
|
|
705
|
+
console.log(`ā³ Request ${index + 1}: Waiting for slot...`);
|
|
706
|
+
await limiter.waitForSlot();
|
|
707
|
+
console.log(`ā
Request ${index + 1}: Got slot, fetching...`);
|
|
708
|
+
|
|
709
|
+
const song = await odesli.fetch(url);
|
|
710
|
+
console.log(`šµ Request ${index + 1}: ${song.title}`);
|
|
711
|
+
return song;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Submit all requests at once - they'll be processed automatically
|
|
715
|
+
(async () => {
|
|
716
|
+
console.log('š Auto-Queue Rate Limiter Demo');
|
|
717
|
+
console.log(
|
|
718
|
+
`š Limit: ${limiter.maxRequests} requests per ${limiter.windowMs / 1000}s`
|
|
719
|
+
);
|
|
720
|
+
console.log(`š Submitting ${urls.length} requests...\n`);
|
|
721
|
+
|
|
722
|
+
// Submit all requests - they'll be processed as slots become available
|
|
723
|
+
const promises = urls.map((url, index) => fetchWithRateLimit(url, index));
|
|
724
|
+
|
|
725
|
+
// Wait for all to complete
|
|
726
|
+
const results = await Promise.all(promises);
|
|
727
|
+
|
|
728
|
+
console.log('\nš All requests completed!');
|
|
729
|
+
console.log(`š Total songs fetched: ${results.length}`);
|
|
730
|
+
})();
|
|
356
731
|
```
|
|
357
732
|
|
|
358
733
|
### 2. Metrics Collector
|
|
@@ -365,13 +740,16 @@ await limiter.waitForSlot(); // Wait for a slot before making a request
|
|
|
365
740
|
- Debug slowdowns or error spikes
|
|
366
741
|
- Gather analytics for reporting or dashboards
|
|
367
742
|
|
|
368
|
-
**
|
|
743
|
+
**CommonJS (require):**
|
|
744
|
+
|
|
745
|
+
```js
|
|
746
|
+
const { MetricsCollector } = require('odesli.js/metrics');
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
**ESM (import):**
|
|
369
750
|
|
|
370
751
|
```js
|
|
371
|
-
|
|
372
|
-
const metrics = new MetricsCollector({ enabled: true });
|
|
373
|
-
metrics.recordRequest({ url, startTime: Date.now(), success: true });
|
|
374
|
-
console.log(metrics.getSummary());
|
|
752
|
+
import { MetricsCollector } from 'odesli.js/metrics';
|
|
375
753
|
```
|
|
376
754
|
|
|
377
755
|
### 3. Plugin System
|
|
@@ -384,18 +762,16 @@ console.log(metrics.getSummary());
|
|
|
384
762
|
- Transform responses or inject custom logic
|
|
385
763
|
- Cleanly separate concerns and enable community plugins
|
|
386
764
|
|
|
387
|
-
**
|
|
765
|
+
**CommonJS (require):**
|
|
388
766
|
|
|
389
767
|
```js
|
|
390
|
-
const PluginSystem = require('
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
});
|
|
398
|
-
await plugins.executeHook('pre-request', { url: '...' });
|
|
768
|
+
const { PluginSystem } = require('odesli.js/plugin-system');
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
**ESM (import):**
|
|
772
|
+
|
|
773
|
+
```js
|
|
774
|
+
import { PluginSystem } from 'odesli.js/plugin-system';
|
|
399
775
|
```
|
|
400
776
|
|
|
401
|
-
See the `examples/advanced-features-example.js` for a full demonstration of these extensions in action.
|
|
777
|
+
See the [`examples/advanced-features-example.js`](./examples/advanced-features-example.js) for a full demonstration of these extensions in action.
|