37 lines
1.3 KiB
JavaScript
37 lines
1.3 KiB
JavaScript
async function fetchCover(query, targetEl) {
|
|
try {
|
|
// In production, this should hit our /api/cover to avoid CORS and add caching,
|
|
// but for the mockup functionality we can use iTunes directly if we don't have backend running.
|
|
// The spec mentioned using server for CORS, but browser often allows GET to iTunes.
|
|
// We will use the backend route to be safe.
|
|
|
|
// For now, simple fallback to iTunes directly if backend is missing.
|
|
let url = `/api/cover?q=${encodeURIComponent(query)}`;
|
|
|
|
// Temporary direct fetch for local testing if no backend
|
|
if (window.location.protocol === 'file:') {
|
|
url = `https://itunes.apple.com/search?term=${encodeURIComponent(query)}&media=music&entity=song&limit=1`;
|
|
}
|
|
|
|
const r = await fetch(url);
|
|
if (!r.ok) throw new Error('fetch error');
|
|
|
|
const data = await r.json();
|
|
let src = '';
|
|
|
|
if (data.url) { // our api
|
|
src = data.url;
|
|
} else if (data.results && data.results[0] && data.results[0].artworkUrl100) { // direct itunes
|
|
src = data.results[0].artworkUrl100.replace('100x100bb', '300x300bb');
|
|
}
|
|
|
|
if (src) {
|
|
targetEl.innerHTML = `<img src="${src}" alt="cover" loading="lazy">`;
|
|
}
|
|
} catch (e) {
|
|
console.error('Cover fetch failed', e);
|
|
}
|
|
}
|
|
|
|
window.fetchCover = fetchCover;
|