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
|
@@ -0,0 +1,205 @@
|
|
|
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('../lib/index.js');
|
|
9
|
+
const { RateLimiter } = require('../lib/rate-limiter.js');
|
|
10
|
+
const { MetricsCollector } = require('../lib/metrics.js');
|
|
11
|
+
const { PluginSystem } = require('../lib/plugin-system.js');
|
|
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();
|
|
@@ -1,66 +1,247 @@
|
|
|
1
|
-
|
|
1
|
+
// Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
|
|
2
|
+
const Odesli = require('../lib');
|
|
3
|
+
const { RateLimiter } = require('../lib/rate-limiter');
|
|
2
4
|
|
|
3
5
|
async function advancedExample() {
|
|
4
|
-
|
|
5
|
-
const apiKey = process.env.ODESLI_API_KEY;
|
|
6
|
-
const odesli = apiKey
|
|
7
|
-
? new Odesli({ apiKey, version: 'v1-alpha.1' })
|
|
8
|
-
: new Odesli();
|
|
6
|
+
console.log('š Advanced Odesli.js Usage Example\n');
|
|
9
7
|
|
|
10
|
-
|
|
8
|
+
// Initialize advanced features
|
|
9
|
+
const rateLimiter = new RateLimiter({
|
|
10
|
+
maxRequests: 8,
|
|
11
|
+
windowMs: 60000,
|
|
12
|
+
strategy: 'token-bucket',
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// Initialize Odesli with advanced configuration (no API key)
|
|
16
|
+
const odesli = new Odesli({
|
|
17
|
+
apiKey: process.env.ODESLI_API_KEY,
|
|
18
|
+
version: 'v1-alpha.1',
|
|
19
|
+
validateParams: true,
|
|
20
|
+
logger: (message, level) => {
|
|
21
|
+
if (level === 'error' || level === 'warn') {
|
|
22
|
+
console.log(`[${level.toUpperCase()}]`, message);
|
|
23
|
+
} else {
|
|
24
|
+
console.log(`[${level.toUpperCase()}]`, message);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// Get the integrated metrics collector
|
|
30
|
+
const metrics = odesli.getMetrics();
|
|
31
|
+
|
|
32
|
+
if (!process.env.ODESLI_API_KEY) {
|
|
11
33
|
console.log(
|
|
12
|
-
'ā¹ļø No API key set. You are limited to 10 requests per minute. Set ODESLI_API_KEY for higher limits.'
|
|
34
|
+
'ā¹ļø No API key set in environment. You are limited to 10 requests per minute. Set ODESLI_API_KEY for higher limits.'
|
|
13
35
|
);
|
|
14
36
|
}
|
|
15
37
|
|
|
16
38
|
try {
|
|
17
|
-
// Example 1:
|
|
18
|
-
console.log('š Fetching song for UK market...');
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
39
|
+
// Example 1: Advanced parameter fetching with metrics
|
|
40
|
+
console.log('š Fetching song for UK market with custom options...');
|
|
41
|
+
|
|
42
|
+
const startTime = Date.now();
|
|
43
|
+
metrics.recordRequest({
|
|
44
|
+
url: 'param-based-request',
|
|
45
|
+
startTime,
|
|
46
|
+
platform: 'spotify',
|
|
47
|
+
country: 'GB',
|
|
48
|
+
});
|
|
24
49
|
|
|
25
|
-
// Example 2: Fetch by parameters
|
|
26
|
-
console.log('\nšÆ Fetching by parameters...');
|
|
27
50
|
const paramSong = await odesli.getByParams(
|
|
28
51
|
'spotify',
|
|
29
52
|
'song',
|
|
30
|
-
'4Km5HrUvYTaSUfiSGPJeQR'
|
|
53
|
+
'4Km5HrUvYTaSUfiSGPJeQR',
|
|
54
|
+
{
|
|
55
|
+
country: 'GB',
|
|
56
|
+
skipCache: false,
|
|
57
|
+
timeout: 5000,
|
|
58
|
+
}
|
|
31
59
|
);
|
|
60
|
+
|
|
61
|
+
metrics.recordRequest({
|
|
62
|
+
url: 'param-based-request',
|
|
63
|
+
startTime,
|
|
64
|
+
endTime: Date.now(),
|
|
65
|
+
success: true,
|
|
66
|
+
statusCode: 200,
|
|
67
|
+
platform: 'spotify',
|
|
68
|
+
country: 'GB',
|
|
69
|
+
});
|
|
70
|
+
|
|
32
71
|
console.log(`Param Title: ${paramSong.title}`);
|
|
72
|
+
console.log();
|
|
73
|
+
|
|
74
|
+
// Example 2: Entity ID fetching with rate limiting
|
|
75
|
+
console.log('š Fetching by entity ID with rate limiting...');
|
|
76
|
+
|
|
77
|
+
await rateLimiter.waitForSlot();
|
|
78
|
+
|
|
79
|
+
const idSong = await odesli.getById(
|
|
80
|
+
'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR',
|
|
81
|
+
{
|
|
82
|
+
country: 'US',
|
|
83
|
+
skipCache: true,
|
|
84
|
+
}
|
|
85
|
+
);
|
|
33
86
|
|
|
34
|
-
// Example 3: Fetch by entity ID
|
|
35
|
-
console.log('\nš Fetching by entity ID...');
|
|
36
|
-
const idSong = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
|
|
37
87
|
console.log(`ID Title: ${idSong.title}`);
|
|
88
|
+
console.log();
|
|
38
89
|
|
|
39
|
-
// Example
|
|
40
|
-
console.log('
|
|
41
|
-
|
|
90
|
+
// Example 3: Enhanced batch fetching with error handling (see below)
|
|
91
|
+
console.log('š Enhanced batch fetching with detailed error handling...');
|
|
92
|
+
|
|
93
|
+
// Example 4: Platform detection and ID extraction
|
|
94
|
+
console.log('š Platform detection and ID extraction...');
|
|
95
|
+
|
|
96
|
+
const testUrls = [
|
|
42
97
|
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
43
|
-
'https://
|
|
98
|
+
'https://music.apple.com/us/album/bad-and-boujee/1440811686?i=1440811687',
|
|
99
|
+
'https://www.youtube.com/watch?v=S-sJp1FfG7Q',
|
|
44
100
|
];
|
|
45
101
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
)
|
|
102
|
+
testUrls.forEach(url => {
|
|
103
|
+
const platform = odesli.detectPlatform(url);
|
|
104
|
+
const id = odesli.extractId(url);
|
|
105
|
+
console.log(`URL: ${url}`);
|
|
106
|
+
console.log(` Platform: ${platform}`);
|
|
107
|
+
console.log(` ID: ${id}`);
|
|
108
|
+
});
|
|
109
|
+
console.log();
|
|
110
|
+
|
|
111
|
+
// Example 5: Supported platforms
|
|
112
|
+
console.log('š± Supported platforms:');
|
|
113
|
+
const platforms = odesli.getSupportedPlatforms();
|
|
114
|
+
console.log(platforms.join(', '));
|
|
115
|
+
console.log();
|
|
116
|
+
|
|
117
|
+
// Example 6: Cache statistics with metrics
|
|
118
|
+
console.log('š Cache and metrics statistics:');
|
|
119
|
+
const cacheStats = odesli.getCacheStats();
|
|
120
|
+
console.log(`Cache hits: ${cacheStats.hitCount}`);
|
|
121
|
+
console.log(`Cache misses: ${cacheStats.missCount}`);
|
|
122
|
+
console.log(`Cache size: ${cacheStats.size}`);
|
|
123
|
+
console.log(`Hit rate: ${(cacheStats.hitRate * 100).toFixed(2)}%`);
|
|
124
|
+
|
|
125
|
+
const metricsSummary = metrics.getSummary();
|
|
126
|
+
console.log(`\nš Metrics Summary (from MetricsCollector):`);
|
|
127
|
+
console.log(` Total requests: ${metricsSummary.counters.totalRequests}`);
|
|
128
|
+
console.log(
|
|
129
|
+
` Success rate: ${(metricsSummary.rates.successRate * 100).toFixed(1)}%`
|
|
50
130
|
);
|
|
131
|
+
console.log(
|
|
132
|
+
` Average response time: ${metricsSummary.recent.avgResponseTime}ms`
|
|
133
|
+
);
|
|
134
|
+
console.log(
|
|
135
|
+
` Requests per minute: ${metricsSummary.recent.requestsPerMinute}`
|
|
136
|
+
);
|
|
137
|
+
console.log();
|
|
51
138
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
139
|
+
// Example 7: User-Agent information
|
|
140
|
+
console.log('š User-Agent information:');
|
|
141
|
+
const userAgent = odesli.getUserAgent();
|
|
142
|
+
console.log(`User-Agent: ${userAgent}`);
|
|
143
|
+
console.log();
|
|
144
|
+
|
|
145
|
+
// Example 8: Plugin system demonstration - requires separate plugin system initialization
|
|
146
|
+
console.log('š Plugin system demonstration:');
|
|
147
|
+
// For this example, we'll create a separate PluginSystem.
|
|
148
|
+
// In a real app, you might integrate it into the Odesli class similarly to MetricsCollector.
|
|
149
|
+
const {
|
|
150
|
+
PluginSystem,
|
|
151
|
+
loggingPlugin,
|
|
152
|
+
analyticsPlugin,
|
|
153
|
+
} = require('../lib/plugin-system');
|
|
154
|
+
const pluginSystem = new PluginSystem();
|
|
155
|
+
pluginSystem.registerPlugin('logging', loggingPlugin);
|
|
156
|
+
pluginSystem.registerPlugin('analytics', analyticsPlugin);
|
|
157
|
+
console.log('Registered plugins:', pluginSystem.getPlugins());
|
|
158
|
+
|
|
159
|
+
pluginSystem.getPlugins().forEach(pluginName => {
|
|
160
|
+
const info = pluginSystem.getPluginInfo(pluginName);
|
|
161
|
+
console.log(` ${pluginName}: ${info.description}`);
|
|
162
|
+
});
|
|
163
|
+
console.log();
|
|
164
|
+
|
|
165
|
+
// Example 9: Error handling with validation
|
|
166
|
+
console.log('ā ļø Testing parameter validation...');
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
await odesli.fetch('invalid-url');
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.log(`Validation error: ${error.message}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
await odesli.getByParams('invalid-platform', 'song', '123');
|
|
176
|
+
} catch (error) {
|
|
177
|
+
console.log(`Platform validation error: ${error.message}`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
await odesli.fetch('https://open.spotify.com/track/123', 'INVALID');
|
|
182
|
+
} catch (error) {
|
|
183
|
+
console.log(`Country validation error: ${error.message}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Batch fetch with enhanced error handling
|
|
187
|
+
console.log(
|
|
188
|
+
'\nš Rate-limited batch fetching with enhanced error handling...'
|
|
189
|
+
);
|
|
190
|
+
const batchUrls = [
|
|
191
|
+
'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
192
|
+
'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
|
|
193
|
+
'https://open.spotify.com/track/1z6WtY7X4HQJvzxC4UgkS1', // Invalid track
|
|
194
|
+
'https://open.spotify.com/track/2CIMQHirSU0MQqyYHq0eOx', // Invalid track
|
|
195
|
+
'https://open.spotify.com/track/3Wrjm47oTz2sjIgck11l5e',
|
|
196
|
+
'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900', // Apple Music with track ID
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
const batchResults = await odesli.fetchBatch(batchUrls, {
|
|
200
|
+
country: 'US',
|
|
201
|
+
concurrency: 3,
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
console.log('\nš Batch Results Summary:');
|
|
205
|
+
let successCount = 0;
|
|
206
|
+
let errorCount = 0;
|
|
207
|
+
|
|
208
|
+
batchResults.forEach((result, index) => {
|
|
209
|
+
if (result.success) {
|
|
210
|
+
successCount++;
|
|
56
211
|
console.log(
|
|
57
|
-
|
|
212
|
+
`ā
Song ${index + 1}: ${result.title} by ${result.artist.join(', ')}`
|
|
58
213
|
);
|
|
214
|
+
} else {
|
|
215
|
+
errorCount++;
|
|
216
|
+
console.log(`ā Song ${index + 1}: ${result.error}`);
|
|
217
|
+
console.log(` Platform: ${result.platform || 'Unknown'}`);
|
|
218
|
+
console.log(` Extracted ID: ${result.extractedId || 'Not found'}`);
|
|
219
|
+
console.log(` Error Type: ${result.errorType}`);
|
|
220
|
+
console.log(` Suggestion: ${result.suggestion}`);
|
|
221
|
+
console.log(` Retryable: ${result.retryable ? 'Yes' : 'No'}`);
|
|
222
|
+
console.log('');
|
|
59
223
|
}
|
|
60
224
|
});
|
|
225
|
+
|
|
226
|
+
console.log(
|
|
227
|
+
`š Batch Summary: ${successCount} successful, ${errorCount} failed`
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
console.log('\nš Advanced usage example completed successfully!');
|
|
61
231
|
} catch (error) {
|
|
62
|
-
|
|
232
|
+
if (
|
|
233
|
+
error.message &&
|
|
234
|
+
(error.message.includes('401') || error.message.includes('429'))
|
|
235
|
+
) {
|
|
236
|
+
console.error('Error:', error.message);
|
|
237
|
+
console.error(
|
|
238
|
+
'You may need an API key for higher limits. See https://odesli.co/'
|
|
239
|
+
);
|
|
240
|
+
} else {
|
|
241
|
+
console.error('ā Error:', error.message);
|
|
242
|
+
}
|
|
63
243
|
}
|
|
64
244
|
}
|
|
65
245
|
|
|
66
|
-
|
|
246
|
+
// Run the example
|
|
247
|
+
advancedExample().catch(console.error);
|
package/examples/basic-usage.js
CHANGED
|
@@ -1,29 +1,104 @@
|
|
|
1
|
-
|
|
1
|
+
// Example: No API key is used. You are limited to 10 requests/minute. Some requests may return 401/429 if the rate limit is exceeded.
|
|
2
|
+
const Odesli = require('../lib');
|
|
3
|
+
// For ESM (import)
|
|
4
|
+
// import { Odesli } from '../lib/index.mjs';
|
|
2
5
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
+
// If you add advanced features:
|
|
7
|
+
// For CommonJS
|
|
8
|
+
// const { RateLimiter } = require('../lib/rate-limiter');
|
|
9
|
+
// const { MetricsCollector } = require('../lib/metrics');
|
|
10
|
+
|
|
11
|
+
// For ESM
|
|
12
|
+
// import { RateLimiter } from '../lib/rate-limiter.mjs';
|
|
13
|
+
// import { MetricsCollector } from '../lib/metrics.mjs';
|
|
14
|
+
|
|
15
|
+
// Initialize without API key (public usage, rate-limited)
|
|
16
|
+
const odesli = new Odesli({
|
|
17
|
+
timeout: 10000,
|
|
18
|
+
cache: true,
|
|
19
|
+
});
|
|
6
20
|
|
|
21
|
+
async function basicExample() {
|
|
7
22
|
try {
|
|
8
|
-
|
|
9
|
-
|
|
23
|
+
console.log('=== Basic Usage Examples ===\n');
|
|
24
|
+
|
|
25
|
+
// Single URL fetch
|
|
26
|
+
console.log('1. Fetching single song...');
|
|
10
27
|
const song = await odesli.fetch(
|
|
11
|
-
'https://open.spotify.com/track/
|
|
28
|
+
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh'
|
|
12
29
|
);
|
|
13
|
-
|
|
14
30
|
console.log(`Title: ${song.title}`);
|
|
15
31
|
console.log(`Artist: ${song.artist.join(', ')}`);
|
|
16
|
-
console.log(`
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
32
|
+
console.log(`Platforms: ${Object.keys(song.linksByPlatform).join(', ')}\n`);
|
|
33
|
+
|
|
34
|
+
// Batch fetch multiple URLs
|
|
35
|
+
console.log('2. Fetching multiple songs...');
|
|
36
|
+
const songs = await odesli.fetch([
|
|
37
|
+
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
38
|
+
'https://music.apple.com/us/album/blinding-lights/1493120897?i=1493120900',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
songs.forEach((song, index) => {
|
|
42
|
+
console.log(
|
|
43
|
+
`Song ${index + 1}: ${song.title} by ${song.artist.join(', ')}`
|
|
44
|
+
);
|
|
24
45
|
});
|
|
46
|
+
console.log();
|
|
47
|
+
|
|
48
|
+
// Get links for specific platform
|
|
49
|
+
console.log('3. Getting Apple Music link...');
|
|
50
|
+
const appleMusicLink = song.linksByPlatform.appleMusic?.url;
|
|
51
|
+
console.log(`Apple Music: ${appleMusicLink}\n`);
|
|
52
|
+
|
|
53
|
+
// Platform detection
|
|
54
|
+
console.log('4. Platform detection...');
|
|
55
|
+
const platform = odesli.detectPlatform(
|
|
56
|
+
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh'
|
|
57
|
+
);
|
|
58
|
+
console.log(`Detected platform: ${platform}\n`);
|
|
59
|
+
|
|
60
|
+
// Country-specific fetch
|
|
61
|
+
console.log('5. Country-specific fetch...');
|
|
62
|
+
const ukSong = await odesli.fetch(
|
|
63
|
+
'https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh',
|
|
64
|
+
{ country: 'GB' }
|
|
65
|
+
);
|
|
66
|
+
console.log(`UK fetch successful: ${ukSong.title}\n`);
|
|
67
|
+
|
|
68
|
+
// Get available country options
|
|
69
|
+
console.log('6. Available country options...');
|
|
70
|
+
const countryOptions = Odesli.getCountryOptions();
|
|
71
|
+
console.log(`Total countries: ${countryOptions.length}`);
|
|
72
|
+
console.log(
|
|
73
|
+
`Sample countries: ${countryOptions
|
|
74
|
+
.slice(0, 5)
|
|
75
|
+
.map(c => `${c.code} (${c.name})`)
|
|
76
|
+
.join(', ')}\n`
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
// Cache statistics
|
|
80
|
+
console.log('7. Cache statistics...');
|
|
81
|
+
const cacheStats = odesli.getCacheStats();
|
|
82
|
+
console.log(`Cache hits: ${cacheStats.hitCount}`);
|
|
83
|
+
console.log(`Cache misses: ${cacheStats.missCount}`);
|
|
84
|
+
console.log(`Cache size: ${cacheStats.size}`);
|
|
85
|
+
console.log(`Hit rate: ${(cacheStats.hitRate * 100).toFixed(2)}%`);
|
|
86
|
+
|
|
87
|
+
// User-Agent information
|
|
88
|
+
console.log('\n8. User-Agent...');
|
|
89
|
+
console.log(`Current User-Agent: ${odesli.getUserAgent()}`);
|
|
25
90
|
} catch (error) {
|
|
26
|
-
|
|
91
|
+
if (
|
|
92
|
+
error.message &&
|
|
93
|
+
(error.message.includes('401') || error.message.includes('429'))
|
|
94
|
+
) {
|
|
95
|
+
console.error('Error:', error.message);
|
|
96
|
+
console.error(
|
|
97
|
+
'You may need an API key for higher limits. See https://odesli.co/'
|
|
98
|
+
);
|
|
99
|
+
} else {
|
|
100
|
+
console.error('Error:', error.message);
|
|
101
|
+
}
|
|
27
102
|
}
|
|
28
103
|
}
|
|
29
104
|
|