odesli.js 1.1.1 → 1.3.1
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/.eslintrc.js +0 -1
- package/.github/workflows/ci.yml +3 -11
- package/.github/workflows/publish-github-packages.yml +46 -0
- package/.github/workflows/{publish.yml → publish-npm.yml} +11 -2
- package/.prettierignore +30 -30
- package/API_IMPROVEMENTS.md +318 -0
- package/CHANGELOG.md +96 -33
- package/LICENSE +14 -14
- package/README.md +212 -144
- package/examples/README.md +197 -26
- package/examples/advanced-features-example.js +205 -0
- package/examples/advanced-usage.js +217 -36
- package/examples/basic-usage.js +92 -17
- package/examples/cache-test.js +119 -0
- package/examples/test-apple-music-extraction.js +60 -0
- package/examples/user-agent-example.js +46 -0
- package/jest.config.js +3 -1
- package/lib/index.d.ts +663 -484
- package/lib/index.js +1274 -390
- package/lib/index.mjs +3 -0
- package/lib/metrics.js +390 -0
- package/lib/metrics.mjs +3 -0
- package/lib/plugin-system.js +382 -0
- package/lib/plugin-system.mjs +3 -0
- package/lib/rate-limiter.js +148 -0
- package/lib/rate-limiter.mjs +3 -0
- package/package.json +2 -1
- package/tests/advanced-features.test.js +423 -0
- package/tests/odesli.test.js +246 -92
- package/tests/setup.js +2 -0
package/README.md
CHANGED
|
@@ -16,26 +16,28 @@ 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 (recommended)](#from-npm-recommended)
|
|
20
|
+
- [From GitHub Packages](#from-github-packages)
|
|
19
21
|
- [Quick Start](#quick-start)
|
|
20
22
|
- [API Key](#api-key)
|
|
21
23
|
- [Usage](#usage)
|
|
22
|
-
- [
|
|
23
|
-
- [Fetch by Parameters](#fetch-by-parameters)
|
|
24
|
-
- [Fetch by Entity ID](#fetch-by-entity-id)
|
|
25
|
-
- [Country-Specific Results](#country-specific-results)
|
|
26
|
-
- [Error Handling](#error-handling)
|
|
24
|
+
- [Basic Usage](#basic-usage)
|
|
27
25
|
- [Advanced Usage](#advanced-usage)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
- [Error Recovery](#error-recovery)
|
|
26
|
+
- [ESM (import)](#esm-import)
|
|
27
|
+
- [CommonJS (require)](#commonjs-require)
|
|
31
28
|
- [Response Format](#response-format)
|
|
32
29
|
- [Supported Platforms](#supported-platforms)
|
|
33
30
|
- [TypeScript Support](#typescript-support)
|
|
34
31
|
- [Examples](#examples)
|
|
32
|
+
- [Quick Examples](#quick-examples)
|
|
35
33
|
- [API Documentation](#api-documentation)
|
|
36
34
|
- [Contributing](#contributing)
|
|
37
35
|
- [License](#license)
|
|
38
36
|
- [Support](#support)
|
|
37
|
+
- [Extensions: Advanced Features](#extensions-advanced-features)
|
|
38
|
+
- [1. Rate Limiter](#1-rate-limiter)
|
|
39
|
+
- [2. Metrics Collector](#2-metrics-collector)
|
|
40
|
+
- [3. Plugin System](#3-plugin-system)
|
|
39
41
|
|
|
40
42
|
## Features
|
|
41
43
|
|
|
@@ -50,10 +52,20 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
|
|
|
50
52
|
|
|
51
53
|
## Installation
|
|
52
54
|
|
|
55
|
+
### From npm (recommended)
|
|
56
|
+
|
|
53
57
|
```bash
|
|
54
58
|
npm install odesli.js
|
|
55
59
|
```
|
|
56
60
|
|
|
61
|
+
### From GitHub Packages
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
npm install @mattraus/odesli.js
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Note**: If you encounter authentication issues, you may need to set up a GitHub token. See [GitHub Packages documentation](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry) for details.
|
|
68
|
+
|
|
57
69
|
## Quick Start
|
|
58
70
|
|
|
59
71
|
```javascript
|
|
@@ -67,6 +79,9 @@ const odesli = new Odesli({
|
|
|
67
79
|
apiKey: 'your-api-key-here',
|
|
68
80
|
version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
|
|
69
81
|
});
|
|
82
|
+
|
|
83
|
+
// You can also disable the metrics collector if you don't need it
|
|
84
|
+
const odesliLight = new Odesli({ metrics: false });
|
|
70
85
|
```
|
|
71
86
|
|
|
72
87
|
## API Key
|
|
@@ -77,161 +92,96 @@ To get an API key, email `developers@song.link`.
|
|
|
77
92
|
|
|
78
93
|
## Usage
|
|
79
94
|
|
|
80
|
-
###
|
|
81
|
-
|
|
82
|
-
Get links for a song using any streaming service URL:
|
|
83
|
-
|
|
84
|
-
```javascript
|
|
85
|
-
// Using async/await
|
|
86
|
-
const song = await odesli.fetch(
|
|
87
|
-
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
88
|
-
);
|
|
89
|
-
console.log(`${song.title} by ${song.artist[0]}`);
|
|
90
|
-
// Output: Bad and Boujee by Migos
|
|
91
|
-
|
|
92
|
-
// Using promises
|
|
93
|
-
odesli
|
|
94
|
-
.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR')
|
|
95
|
-
.then(song => {
|
|
96
|
-
console.log(`${song.title} by ${song.artist[0]}`);
|
|
97
|
-
});
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
### Fetch by Parameters
|
|
101
|
-
|
|
102
|
-
Get links using platform, type, and ID:
|
|
95
|
+
### Basic Usage
|
|
103
96
|
|
|
104
97
|
```javascript
|
|
105
|
-
|
|
106
|
-
const song = await odesli.getByParams(
|
|
107
|
-
'spotify',
|
|
108
|
-
'song',
|
|
109
|
-
'4Km5HrUvYTaSUfiSGPJeQR'
|
|
110
|
-
);
|
|
111
|
-
console.log(song.artist[0]); // Output: Migos
|
|
112
|
-
|
|
113
|
-
// Using promises
|
|
114
|
-
odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR').then(song => {
|
|
115
|
-
console.log(song.artist[0]);
|
|
116
|
-
});
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
### Fetch by Entity ID
|
|
120
|
-
|
|
121
|
-
Get links using the full entity ID:
|
|
98
|
+
const Odesli = require('odesli.js');
|
|
122
99
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
126
|
-
console.log(song.title); // Output: Bad and Boujee
|
|
100
|
+
// Initialize without API key (10 requests/minute limit)
|
|
101
|
+
const odesli = new Odesli();
|
|
127
102
|
|
|
128
|
-
//
|
|
129
|
-
odesli
|
|
130
|
-
|
|
103
|
+
// Or with API key for higher limits
|
|
104
|
+
const odesli = new Odesli({
|
|
105
|
+
apiKey: 'your-api-key-here',
|
|
131
106
|
});
|
|
132
|
-
```
|
|
133
107
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
All methods accept an optional country parameter (ISO 3166-1 Alpha-2 code):
|
|
137
|
-
|
|
138
|
-
```javascript
|
|
139
|
-
// Get results for the United Kingdom
|
|
108
|
+
// Fetch a song by URL
|
|
140
109
|
const song = await odesli.fetch(
|
|
141
|
-
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
142
|
-
'GB'
|
|
110
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
143
111
|
);
|
|
112
|
+
console.log(`${song.title} by ${song.artist.join(', ')}`);
|
|
144
113
|
|
|
145
|
-
//
|
|
146
|
-
const
|
|
147
|
-
'spotify',
|
|
148
|
-
'
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
);
|
|
114
|
+
// Fetch multiple songs at once
|
|
115
|
+
const urls = [
|
|
116
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
117
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
118
|
+
];
|
|
119
|
+
const songs = await odesli.fetch(urls);
|
|
120
|
+
songs.forEach(song => console.log(song.title));
|
|
152
121
|
```
|
|
153
122
|
|
|
154
|
-
###
|
|
155
|
-
|
|
156
|
-
The library throws descriptive errors for various scenarios:
|
|
123
|
+
### Advanced Usage
|
|
157
124
|
|
|
158
125
|
```javascript
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
126
|
+
// Initialize with custom options
|
|
127
|
+
const odesli = new Odesli({
|
|
128
|
+
apiKey: 'your-api-key-here',
|
|
129
|
+
version: 'v1-alpha.1',
|
|
130
|
+
cache: true,
|
|
131
|
+
timeout: 10000,
|
|
132
|
+
maxRetries: 3,
|
|
133
|
+
retryDelay: 1000,
|
|
134
|
+
headers: { 'User-Agent': 'MyApp/1.0' },
|
|
135
|
+
validateParams: true,
|
|
136
|
+
logger: (message, level) => console.log(`[${level}] ${message}`),
|
|
137
|
+
});
|
|
171
138
|
|
|
172
|
-
|
|
139
|
+
// Fetch with options
|
|
140
|
+
const song = await odesli.fetch('https://open.spotify.com/track/123', {
|
|
141
|
+
country: 'GB',
|
|
142
|
+
skipCache: false,
|
|
143
|
+
timeout: 5000,
|
|
144
|
+
});
|
|
173
145
|
|
|
174
|
-
|
|
175
|
-
// Process multiple songs efficiently
|
|
146
|
+
// Batch fetch with concurrency control
|
|
176
147
|
const urls = [
|
|
177
|
-
'https://open.spotify.com/track/
|
|
178
|
-
'https://
|
|
179
|
-
'https://
|
|
148
|
+
'https://open.spotify.com/track/123',
|
|
149
|
+
'https://music.apple.com/us/album/test/456?i=789',
|
|
150
|
+
'https://www.youtube.com/watch?v=abc123',
|
|
180
151
|
];
|
|
181
152
|
|
|
182
|
-
const songs = await
|
|
153
|
+
const songs = await odesli.fetch(urls, {
|
|
154
|
+
country: 'US',
|
|
155
|
+
concurrency: 3,
|
|
156
|
+
skipCache: true,
|
|
157
|
+
});
|
|
183
158
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
159
|
+
// Handle errors in batch results
|
|
160
|
+
songs.forEach((song, index) => {
|
|
161
|
+
if (song.error) {
|
|
162
|
+
console.log(`Song ${index + 1}: Error - ${song.error}`);
|
|
187
163
|
} else {
|
|
188
|
-
console.log(`Song ${index + 1}:
|
|
164
|
+
console.log(`Song ${index + 1}: ${song.title}`);
|
|
189
165
|
}
|
|
190
166
|
});
|
|
191
167
|
```
|
|
192
168
|
|
|
193
|
-
|
|
169
|
+
### ESM (import)
|
|
194
170
|
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
// Extract all platform URLs
|
|
202
|
-
const platformUrls = Object.entries(song.linksByPlatform).map(
|
|
203
|
-
([platform, data]) => ({
|
|
204
|
-
platform,
|
|
205
|
-
url: data.url,
|
|
206
|
-
mobileUri: data.nativeAppUriMobile,
|
|
207
|
-
desktopUri: data.nativeAppUriDesktop,
|
|
208
|
-
})
|
|
209
|
-
);
|
|
210
|
-
|
|
211
|
-
console.log('Available platforms:', platformUrls);
|
|
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';
|
|
212
176
|
```
|
|
213
177
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
```javascript
|
|
217
|
-
async function fetchWithRetry(url, maxRetries = 3) {
|
|
218
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
219
|
-
try {
|
|
220
|
-
return await odesli.fetch(url);
|
|
221
|
-
} catch (error) {
|
|
222
|
-
if (attempt === maxRetries) throw error;
|
|
223
|
-
|
|
224
|
-
// Wait before retrying (exponential backoff)
|
|
225
|
-
await new Promise(resolve => setTimeout(resolve, attempt * 1000));
|
|
226
|
-
console.log(`Retry attempt ${attempt} for ${url}`);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
}
|
|
178
|
+
### CommonJS (require)
|
|
230
179
|
|
|
231
|
-
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
);
|
|
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');
|
|
235
185
|
```
|
|
236
186
|
|
|
237
187
|
## Response Format
|
|
@@ -293,26 +243,77 @@ All methods return a response object with the following structure:
|
|
|
293
243
|
|
|
294
244
|
## TypeScript Support
|
|
295
245
|
|
|
296
|
-
This package includes full TypeScript definitions:
|
|
246
|
+
This package includes full TypeScript definitions with strict country code validation:
|
|
297
247
|
|
|
298
248
|
```typescript
|
|
299
|
-
import Odesli from 'odesli.js';
|
|
249
|
+
import Odesli, { CountryCode } from 'odesli.js';
|
|
300
250
|
|
|
301
251
|
const odesli = new Odesli({ apiKey: 'your-key' });
|
|
302
|
-
|
|
303
|
-
//
|
|
252
|
+
|
|
253
|
+
// TypeScript enforces valid country codes
|
|
254
|
+
const song = await odesli.fetch('https://open.spotify.com/track/...', {
|
|
255
|
+
country: 'US', // ✅ Valid - TypeScript autocomplete shows all valid codes
|
|
256
|
+
// country: 'INVALID' // ❌ TypeScript error - not a valid CountryCode
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
// Get all valid country codes and names for UI dropdowns
|
|
260
|
+
const countryOptions = Odesli.getCountryOptions();
|
|
261
|
+
// Returns: [{ code: 'US', name: 'United States' }, { code: 'GB', name: 'United Kingdom' }, ...]
|
|
304
262
|
```
|
|
305
263
|
|
|
306
264
|
## Examples
|
|
307
265
|
|
|
308
|
-
Check out the [examples directory](./examples) for
|
|
266
|
+
Check out the [examples directory](./examples) for comprehensive usage examples:
|
|
267
|
+
|
|
268
|
+
- [Basic Usage](./examples/basic-usage.js) - Simple song fetching with country options
|
|
269
|
+
- [Advanced Features](./examples/advanced-features-example.js) - Rate limiting, metrics, and plugin system
|
|
270
|
+
- [User Agent Example](./examples/user-agent-example.js) - Custom headers and User-Agent usage
|
|
271
|
+
|
|
272
|
+
### Quick Examples
|
|
273
|
+
|
|
274
|
+
**Country-specific fetching:**
|
|
275
|
+
|
|
276
|
+
```javascript
|
|
277
|
+
// Get country options for UI dropdowns
|
|
278
|
+
const countries = Odesli.getCountryOptions();
|
|
279
|
+
console.log(`Available countries: ${countries.length}`);
|
|
280
|
+
|
|
281
|
+
// Fetch with specific country
|
|
282
|
+
const song = await odesli.fetch('https://spotify.com/track/123', {
|
|
283
|
+
country: 'GB', // United Kingdom
|
|
284
|
+
});
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
**Batch fetching with error handling:**
|
|
288
|
+
|
|
289
|
+
```javascript
|
|
290
|
+
const urls = [
|
|
291
|
+
'https://open.spotify.com/track/123',
|
|
292
|
+
'https://music.apple.com/us/album/test/456?i=789',
|
|
293
|
+
];
|
|
294
|
+
|
|
295
|
+
const results = await odesli.fetch(urls, { country: 'US' });
|
|
296
|
+
|
|
297
|
+
results.forEach((result, index) => {
|
|
298
|
+
if (result.error) {
|
|
299
|
+
console.log(`Song ${index + 1}: Error - ${result.error}`);
|
|
300
|
+
} else {
|
|
301
|
+
console.log(`Song ${index + 1}: ${result.title}`);
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
```
|
|
309
305
|
|
|
310
|
-
|
|
311
|
-
|
|
306
|
+
**Platform detection and ID extraction:**
|
|
307
|
+
|
|
308
|
+
```javascript
|
|
309
|
+
const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
|
|
310
|
+
const id = odesli.extractId('https://open.spotify.com/track/123');
|
|
311
|
+
console.log(`Platform: ${platform}, ID: ${id}`);
|
|
312
|
+
```
|
|
312
313
|
|
|
313
314
|
## API Documentation
|
|
314
315
|
|
|
315
|
-
For more detailed information about the Odesli API, check the [official documentation](https://
|
|
316
|
+
For more detailed information about the Odesli API, check the [official documentation](https://linktree.notion.site/API-d0ebe08a5e304a55928405eb682f6741).
|
|
316
317
|
|
|
317
318
|
## Contributing
|
|
318
319
|
|
|
@@ -330,4 +331,71 @@ This project is licensed under the ISC License - see the [LICENSE](LICENSE) file
|
|
|
330
331
|
|
|
331
332
|
- 📧 Email: `developers@song.link` (for API key requests)
|
|
332
333
|
- 🐛 Issues: [GitHub Issues](https://github.com/MattrAus/odesli.js/issues)
|
|
333
|
-
- 📖 Documentation: [Odesli API Docs](https://
|
|
334
|
+
- 📖 Documentation: [Odesli API Docs](https://linktree.notion.site/API-d0ebe08a5e304a55928405eb682f6741)
|
|
335
|
+
|
|
336
|
+
## Extensions: Advanced Features
|
|
337
|
+
|
|
338
|
+
Odesli.js provides several advanced extensions to help you build robust, scalable, and customizable integrations:
|
|
339
|
+
|
|
340
|
+
### 1. Rate Limiter
|
|
341
|
+
|
|
342
|
+
**What:** Controls the number of API requests per time window using strategies like token bucket, leaky bucket, or sliding window.
|
|
343
|
+
|
|
344
|
+
**Why use it?**
|
|
345
|
+
|
|
346
|
+
- Prevents hitting Odesli/Songlink API rate limits
|
|
347
|
+
- Smooths out traffic spikes
|
|
348
|
+
- Ensures fair usage in multi-user or batch scenarios
|
|
349
|
+
|
|
350
|
+
**Example:**
|
|
351
|
+
|
|
352
|
+
```js
|
|
353
|
+
const RateLimiter = require('./lib/rate-limiter');
|
|
354
|
+
const limiter = new RateLimiter({ maxRequests: 10, windowMs: 60000 });
|
|
355
|
+
await limiter.waitForSlot(); // Wait for a slot before making a request
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
### 2. Metrics Collector
|
|
359
|
+
|
|
360
|
+
**What:** Tracks requests, errors, cache hits, response times, and rate limit events.
|
|
361
|
+
|
|
362
|
+
**Why use it?**
|
|
363
|
+
|
|
364
|
+
- Monitor API usage and performance
|
|
365
|
+
- Debug slowdowns or error spikes
|
|
366
|
+
- Gather analytics for reporting or dashboards
|
|
367
|
+
|
|
368
|
+
**Example:**
|
|
369
|
+
|
|
370
|
+
```js
|
|
371
|
+
const MetricsCollector = require('./lib/metrics');
|
|
372
|
+
const metrics = new MetricsCollector({ enabled: true });
|
|
373
|
+
metrics.recordRequest({ url, startTime: Date.now(), success: true });
|
|
374
|
+
console.log(metrics.getSummary());
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### 3. Plugin System
|
|
378
|
+
|
|
379
|
+
**What:** Extensible system for adding hooks, middleware, and data transformers to Odesli.js.
|
|
380
|
+
|
|
381
|
+
**Why use it?**
|
|
382
|
+
|
|
383
|
+
- Add custom logging, analytics, or caching
|
|
384
|
+
- Transform responses or inject custom logic
|
|
385
|
+
- Cleanly separate concerns and enable community plugins
|
|
386
|
+
|
|
387
|
+
**Example:**
|
|
388
|
+
|
|
389
|
+
```js
|
|
390
|
+
const PluginSystem = require('./lib/plugin-system');
|
|
391
|
+
const plugins = new PluginSystem();
|
|
392
|
+
plugins.registerPlugin('logger', {
|
|
393
|
+
hooks: {
|
|
394
|
+
'pre-request': ctx => console.log('Requesting:', ctx.url),
|
|
395
|
+
'post-response': ctx => console.log('Response:', ctx.url),
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
await plugins.executeHook('pre-request', { url: '...' });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
See the `examples/advanced-features-example.js` for a full demonstration of these extensions in action.
|
package/examples/README.md
CHANGED
|
@@ -1,50 +1,221 @@
|
|
|
1
|
-
# Examples
|
|
1
|
+
# Odesli.js Examples
|
|
2
2
|
|
|
3
|
-
This directory contains
|
|
3
|
+
This directory contains examples demonstrating how to use the Odesli.js library.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Examples
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
### Basic Usage (`basic-usage.js`)
|
|
8
|
+
|
|
9
|
+
Demonstrates the fundamental usage of the library:
|
|
10
|
+
|
|
11
|
+
- Single URL fetching
|
|
12
|
+
- Batch URL fetching with the unified API
|
|
13
|
+
- Basic error handling
|
|
8
14
|
|
|
9
15
|
```bash
|
|
10
16
|
node examples/basic-usage.js
|
|
11
17
|
```
|
|
12
18
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
- Initializing the Odesli client
|
|
16
|
-
- Fetching a song by URL
|
|
17
|
-
- Displaying song information
|
|
18
|
-
- Showing available streaming platforms
|
|
19
|
+
### Advanced Usage (`advanced-usage.js`)
|
|
19
20
|
|
|
20
|
-
|
|
21
|
+
Shows advanced features and configurations:
|
|
21
22
|
|
|
22
|
-
|
|
23
|
+
- Custom client configuration
|
|
24
|
+
- Platform detection and ID extraction
|
|
25
|
+
- Cache management
|
|
26
|
+
- Unified fetch API for both single and batch operations
|
|
27
|
+
- Error handling and recovery
|
|
28
|
+
- **NEW**: Rate limiting integration
|
|
29
|
+
- **NEW**: Metrics collection
|
|
30
|
+
- **NEW**: Plugin system demonstration
|
|
23
31
|
|
|
24
32
|
```bash
|
|
25
33
|
node examples/advanced-usage.js
|
|
26
34
|
```
|
|
27
35
|
|
|
28
|
-
|
|
29
|
-
|
|
36
|
+
### Advanced Features (`advanced-features-example.js`)
|
|
37
|
+
|
|
38
|
+
Comprehensive demonstration of enterprise-grade features:
|
|
39
|
+
|
|
40
|
+
- Rate limiting with multiple strategies
|
|
41
|
+
- Comprehensive metrics collection and analysis
|
|
42
|
+
- Plugin system with hooks and middleware
|
|
43
|
+
- Error handling with plugins
|
|
44
|
+
- Performance monitoring
|
|
30
45
|
|
|
31
46
|
```bash
|
|
32
|
-
|
|
33
|
-
|
|
47
|
+
node examples/advanced-features-example.js
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### User-Agent Example (`user-agent-example.js`)
|
|
51
|
+
|
|
52
|
+
Shows how to work with User-Agent headers:
|
|
53
|
+
|
|
54
|
+
- Default User-Agent generation
|
|
55
|
+
- Custom header overrides
|
|
56
|
+
- Platform and version information
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
node examples/user-agent-example.js
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Key Features Demonstrated
|
|
63
|
+
|
|
64
|
+
### Unified Fetch API
|
|
65
|
+
|
|
66
|
+
The `fetch()` method now supports both single URLs and arrays of URLs:
|
|
67
|
+
|
|
68
|
+
```javascript
|
|
69
|
+
// Single fetch
|
|
70
|
+
const song = await odesli.fetch('https://open.spotify.com/track/123');
|
|
71
|
+
|
|
72
|
+
// Batch fetch
|
|
73
|
+
const songs = await odesli.fetch([
|
|
74
|
+
'https://open.spotify.com/track/123',
|
|
75
|
+
'https://open.spotify.com/track/456',
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
// Batch fetch with options
|
|
79
|
+
const songs = await odesli.fetch(urls, {
|
|
80
|
+
country: 'GB',
|
|
81
|
+
concurrency: 3,
|
|
82
|
+
skipCache: true,
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Rate Limiting
|
|
87
|
+
|
|
88
|
+
Built-in rate limiting with multiple strategies:
|
|
89
|
+
|
|
90
|
+
```javascript
|
|
91
|
+
const RateLimiter = require('../lib/rate-limiter.js');
|
|
92
|
+
|
|
93
|
+
const rateLimiter = new RateLimiter({
|
|
94
|
+
maxRequests: 10,
|
|
95
|
+
windowMs: 60000, // 1 minute
|
|
96
|
+
strategy: 'token-bucket', // or 'leaky-bucket', 'sliding-window'
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Wait for available slot
|
|
100
|
+
await rateLimiter.waitForSlot();
|
|
101
|
+
const song = await odesli.fetch(url);
|
|
34
102
|
```
|
|
35
103
|
|
|
36
|
-
|
|
104
|
+
### Metrics Collection
|
|
37
105
|
|
|
38
|
-
|
|
39
|
-
- Fetching songs for different countries
|
|
40
|
-
- Using different methods (fetch, getByParams, getById)
|
|
41
|
-
- Processing multiple songs in parallel
|
|
42
|
-
- Error handling
|
|
106
|
+
Comprehensive metrics tracking:
|
|
43
107
|
|
|
44
|
-
|
|
108
|
+
```javascript
|
|
109
|
+
const MetricsCollector = require('../lib/metrics.js');
|
|
45
110
|
|
|
46
|
-
|
|
111
|
+
const metrics = new MetricsCollector({
|
|
112
|
+
enabled: true,
|
|
113
|
+
retentionMs: 24 * 60 * 60 * 1000, // 24 hours
|
|
114
|
+
});
|
|
47
115
|
|
|
48
|
-
|
|
116
|
+
// Record request
|
|
117
|
+
metrics.recordRequest({
|
|
118
|
+
url: 'https://example.com',
|
|
119
|
+
startTime: Date.now(),
|
|
120
|
+
success: true,
|
|
121
|
+
platform: 'spotify',
|
|
122
|
+
country: 'US',
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Get summary
|
|
126
|
+
const summary = metrics.getSummary();
|
|
127
|
+
console.log(`Success rate: ${summary.rates.successRate}%`);
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Plugin System
|
|
131
|
+
|
|
132
|
+
Extensible functionality through plugins:
|
|
133
|
+
|
|
134
|
+
```javascript
|
|
135
|
+
const { PluginSystem, loggingPlugin } = require('../lib/plugin-system.js');
|
|
136
|
+
|
|
137
|
+
const pluginSystem = new PluginSystem();
|
|
138
|
+
pluginSystem.registerPlugin('logging', loggingPlugin);
|
|
139
|
+
|
|
140
|
+
// Execute hooks
|
|
141
|
+
await pluginSystem.executeHook('beforeRequest', { url: 'https://example.com' });
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Error Handling
|
|
145
|
+
|
|
146
|
+
Batch operations gracefully handle errors:
|
|
147
|
+
|
|
148
|
+
```javascript
|
|
149
|
+
const results = await odesli.fetch(urls);
|
|
150
|
+
results.forEach((result, index) => {
|
|
151
|
+
if (result.error) {
|
|
152
|
+
console.log(`Song ${index + 1}: Error - ${result.error}`);
|
|
153
|
+
} else {
|
|
154
|
+
console.log(`Song ${index + 1}: ${result.title}`);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Platform Detection
|
|
160
|
+
|
|
161
|
+
Utility methods for working with URLs:
|
|
162
|
+
|
|
163
|
+
```javascript
|
|
164
|
+
const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
|
|
165
|
+
const id = odesli.extractId('https://open.spotify.com/track/123');
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Advanced Features
|
|
169
|
+
|
|
170
|
+
### Rate Limiting Strategies
|
|
171
|
+
|
|
172
|
+
1. **Token Bucket** (default): Best for burst handling
|
|
173
|
+
2. **Leaky Bucket**: Smooths out traffic
|
|
174
|
+
3. **Sliding Window**: Most accurate rate limiting
|
|
175
|
+
|
|
176
|
+
### Metrics Analysis
|
|
177
|
+
|
|
178
|
+
- **Real-time counters**: Total requests, success/failure rates
|
|
179
|
+
- **Performance metrics**: Response times, throughput
|
|
180
|
+
- **Cache analytics**: Hit rates, cache efficiency
|
|
181
|
+
- **Platform analysis**: Usage by platform and country
|
|
182
|
+
- **Error tracking**: Error patterns and frequency
|
|
183
|
+
|
|
184
|
+
### Plugin System Features
|
|
185
|
+
|
|
186
|
+
- **Hooks**: Execute code at specific points (beforeRequest, afterRequest, onError, etc.)
|
|
187
|
+
- **Middleware**: Process requests through a chain
|
|
188
|
+
- **Transformers**: Modify response data
|
|
189
|
+
- **Built-in plugins**: Logging, caching, analytics, response transformation
|
|
190
|
+
|
|
191
|
+
## Running Examples
|
|
192
|
+
|
|
193
|
+
Make sure you have the library installed and configured before running examples:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
npm install
|
|
197
|
+
node examples/basic-usage.js
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Environment Variables
|
|
201
|
+
|
|
202
|
+
Some examples use environment variables:
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
# Optional: Set API key for higher rate limits
|
|
206
|
+
export ODESLI_API_KEY=your-api-key-here
|
|
207
|
+
|
|
208
|
+
# Run advanced examples
|
|
209
|
+
node examples/advanced-features-example.js
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### Testing Advanced Features
|
|
213
|
+
|
|
214
|
+
Run the comprehensive test suite:
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
npm test
|
|
218
|
+
npm test -- --testNamePattern="Advanced Features"
|
|
219
|
+
```
|
|
49
220
|
|
|
50
|
-
|
|
221
|
+
Note: Some examples make actual API calls and may be subject to rate limiting without an API key. The rate limiting examples demonstrate how to handle this gracefully.
|