odesli.js 1.1.2 → 1.3.2
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/workflows/ci.yml +0 -8
- package/.github/workflows/publish-github-packages.yml +8 -12
- package/.github/workflows/publish-npm.yml +1 -1
- package/API_IMPROVEMENTS.md +318 -0
- package/CHANGELOG.md +83 -56
- package/README.md +201 -156
- 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 +476 -297
- package/lib/index.js +1041 -157
- 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
|
|
|
@@ -62,20 +64,7 @@ npm install odesli.js
|
|
|
62
64
|
npm install @mattraus/odesli.js
|
|
63
65
|
```
|
|
64
66
|
|
|
65
|
-
**Note**:
|
|
66
|
-
|
|
67
|
-
```
|
|
68
|
-
@mattraus:registry=https://npm.pkg.github.com
|
|
69
|
-
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
Then set your GitHub token as an environment variable:
|
|
73
|
-
|
|
74
|
-
```bash
|
|
75
|
-
export GITHUB_TOKEN=your_github_token_here
|
|
76
|
-
# or on Windows:
|
|
77
|
-
# set GITHUB_TOKEN=your_github_token_here
|
|
78
|
-
```
|
|
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.
|
|
79
68
|
|
|
80
69
|
## Quick Start
|
|
81
70
|
|
|
@@ -90,6 +79,9 @@ const odesli = new Odesli({
|
|
|
90
79
|
apiKey: 'your-api-key-here',
|
|
91
80
|
version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
|
|
92
81
|
});
|
|
82
|
+
|
|
83
|
+
// You can also disable the metrics collector if you don't need it
|
|
84
|
+
const odesliLight = new Odesli({ metrics: false });
|
|
93
85
|
```
|
|
94
86
|
|
|
95
87
|
## API Key
|
|
@@ -100,161 +92,96 @@ To get an API key, email `developers@song.link`.
|
|
|
100
92
|
|
|
101
93
|
## Usage
|
|
102
94
|
|
|
103
|
-
###
|
|
104
|
-
|
|
105
|
-
Get links for a song using any streaming service URL:
|
|
106
|
-
|
|
107
|
-
```javascript
|
|
108
|
-
// Using async/await
|
|
109
|
-
const song = await odesli.fetch(
|
|
110
|
-
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
111
|
-
);
|
|
112
|
-
console.log(`${song.title} by ${song.artist[0]}`);
|
|
113
|
-
// Output: Bad and Boujee by Migos
|
|
114
|
-
|
|
115
|
-
// Using promises
|
|
116
|
-
odesli
|
|
117
|
-
.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR')
|
|
118
|
-
.then(song => {
|
|
119
|
-
console.log(`${song.title} by ${song.artist[0]}`);
|
|
120
|
-
});
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
### Fetch by Parameters
|
|
124
|
-
|
|
125
|
-
Get links using platform, type, and ID:
|
|
95
|
+
### Basic Usage
|
|
126
96
|
|
|
127
97
|
```javascript
|
|
128
|
-
|
|
129
|
-
const song = await odesli.getByParams(
|
|
130
|
-
'spotify',
|
|
131
|
-
'song',
|
|
132
|
-
'4Km5HrUvYTaSUfiSGPJeQR'
|
|
133
|
-
);
|
|
134
|
-
console.log(song.artist[0]); // Output: Migos
|
|
135
|
-
|
|
136
|
-
// Using promises
|
|
137
|
-
odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR').then(song => {
|
|
138
|
-
console.log(song.artist[0]);
|
|
139
|
-
});
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
### Fetch by Entity ID
|
|
143
|
-
|
|
144
|
-
Get links using the full entity ID:
|
|
98
|
+
const Odesli = require('odesli.js');
|
|
145
99
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
149
|
-
console.log(song.title); // Output: Bad and Boujee
|
|
100
|
+
// Initialize without API key (10 requests/minute limit)
|
|
101
|
+
const odesli = new Odesli();
|
|
150
102
|
|
|
151
|
-
//
|
|
152
|
-
odesli
|
|
153
|
-
|
|
103
|
+
// Or with API key for higher limits
|
|
104
|
+
const odesli = new Odesli({
|
|
105
|
+
apiKey: 'your-api-key-here',
|
|
154
106
|
});
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
### Country-Specific Results
|
|
158
107
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
```javascript
|
|
162
|
-
// Get results for the United Kingdom
|
|
108
|
+
// Fetch a song by URL
|
|
163
109
|
const song = await odesli.fetch(
|
|
164
|
-
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
165
|
-
'GB'
|
|
110
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
166
111
|
);
|
|
112
|
+
console.log(`${song.title} by ${song.artist.join(', ')}`);
|
|
167
113
|
|
|
168
|
-
//
|
|
169
|
-
const
|
|
170
|
-
'spotify',
|
|
171
|
-
'
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
);
|
|
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));
|
|
175
121
|
```
|
|
176
122
|
|
|
177
|
-
###
|
|
178
|
-
|
|
179
|
-
The library throws descriptive errors for various scenarios:
|
|
123
|
+
### Advanced Usage
|
|
180
124
|
|
|
181
125
|
```javascript
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
+
});
|
|
194
138
|
|
|
195
|
-
|
|
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
|
+
});
|
|
196
145
|
|
|
197
|
-
|
|
198
|
-
// Process multiple songs efficiently
|
|
146
|
+
// Batch fetch with concurrency control
|
|
199
147
|
const urls = [
|
|
200
|
-
'https://open.spotify.com/track/
|
|
201
|
-
'https://
|
|
202
|
-
'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',
|
|
203
151
|
];
|
|
204
152
|
|
|
205
|
-
const songs = await
|
|
153
|
+
const songs = await odesli.fetch(urls, {
|
|
154
|
+
country: 'US',
|
|
155
|
+
concurrency: 3,
|
|
156
|
+
skipCache: true,
|
|
157
|
+
});
|
|
206
158
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
159
|
+
// Handle errors in batch results
|
|
160
|
+
songs.forEach((song, index) => {
|
|
161
|
+
if (song.error) {
|
|
162
|
+
console.log(`Song ${index + 1}: Error - ${song.error}`);
|
|
210
163
|
} else {
|
|
211
|
-
console.log(`Song ${index + 1}:
|
|
164
|
+
console.log(`Song ${index + 1}: ${song.title}`);
|
|
212
165
|
}
|
|
213
166
|
});
|
|
214
167
|
```
|
|
215
168
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
```javascript
|
|
219
|
-
// Get all available platform links
|
|
220
|
-
const song = await odesli.fetch(
|
|
221
|
-
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
|
|
222
|
-
);
|
|
223
|
-
|
|
224
|
-
// Extract all platform URLs
|
|
225
|
-
const platformUrls = Object.entries(song.linksByPlatform).map(
|
|
226
|
-
([platform, data]) => ({
|
|
227
|
-
platform,
|
|
228
|
-
url: data.url,
|
|
229
|
-
mobileUri: data.nativeAppUriMobile,
|
|
230
|
-
desktopUri: data.nativeAppUriDesktop,
|
|
231
|
-
})
|
|
232
|
-
);
|
|
169
|
+
### ESM (import)
|
|
233
170
|
|
|
234
|
-
|
|
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';
|
|
235
176
|
```
|
|
236
177
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
```javascript
|
|
240
|
-
async function fetchWithRetry(url, maxRetries = 3) {
|
|
241
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
242
|
-
try {
|
|
243
|
-
return await odesli.fetch(url);
|
|
244
|
-
} catch (error) {
|
|
245
|
-
if (attempt === maxRetries) throw error;
|
|
246
|
-
|
|
247
|
-
// Wait before retrying (exponential backoff)
|
|
248
|
-
await new Promise(resolve => setTimeout(resolve, attempt * 1000));
|
|
249
|
-
console.log(`Retry attempt ${attempt} for ${url}`);
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
178
|
+
### CommonJS (require)
|
|
253
179
|
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
);
|
|
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');
|
|
258
185
|
```
|
|
259
186
|
|
|
260
187
|
## Response Format
|
|
@@ -316,22 +243,73 @@ All methods return a response object with the following structure:
|
|
|
316
243
|
|
|
317
244
|
## TypeScript Support
|
|
318
245
|
|
|
319
|
-
This package includes full TypeScript definitions:
|
|
246
|
+
This package includes full TypeScript definitions with strict country code validation:
|
|
320
247
|
|
|
321
248
|
```typescript
|
|
322
|
-
import Odesli from 'odesli.js';
|
|
249
|
+
import Odesli, { CountryCode } from 'odesli.js';
|
|
323
250
|
|
|
324
251
|
const odesli = new Odesli({ apiKey: 'your-key' });
|
|
325
|
-
|
|
326
|
-
//
|
|
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' }, ...]
|
|
327
262
|
```
|
|
328
263
|
|
|
329
264
|
## Examples
|
|
330
265
|
|
|
331
|
-
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
|
+
```
|
|
305
|
+
|
|
306
|
+
**Platform detection and ID extraction:**
|
|
332
307
|
|
|
333
|
-
|
|
334
|
-
|
|
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
|
+
```
|
|
335
313
|
|
|
336
314
|
## API Documentation
|
|
337
315
|
|
|
@@ -354,3 +332,70 @@ This project is licensed under the ISC License - see the [LICENSE](LICENSE) file
|
|
|
354
332
|
- 📧 Email: `developers@song.link` (for API key requests)
|
|
355
333
|
- 🐛 Issues: [GitHub Issues](https://github.com/MattrAus/odesli.js/issues)
|
|
356
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.
|