|
| 1 | +import { connectToDatabase } from '$lib/db'; |
| 2 | +import fetch from 'node-fetch'; |
| 3 | +import { ObjectId } from 'mongodb'; |
| 4 | +import { json } from '@sveltejs/kit'; // Import the json utility |
| 5 | + |
| 6 | +export async function GET({ url }) { |
| 7 | + const query = url.searchParams.get('query'); |
| 8 | + if (!query) { |
| 9 | + return json({ error: 'Query parameter is required' }, { status: 400 }); |
| 10 | + } |
| 11 | + |
| 12 | + const { db } = await connectToDatabase(); |
| 13 | + |
| 14 | + // Check if the search query is already cached |
| 15 | + const cachedSearch = await db.collection('searches').findOne({ query }); |
| 16 | + |
| 17 | + if (cachedSearch) { |
| 18 | + // Fetch cached results from the Songs collection |
| 19 | + const songIds = cachedSearch.results.map(id => new ObjectId(id)); |
| 20 | + const songs = await db.collection('songs').find({ _id: { $in: songIds } }).toArray(); |
| 21 | + return json({ songs }); |
| 22 | + } |
| 23 | + |
| 24 | + // If not cached, fetch from MusicBrainz API |
| 25 | + const response = await fetch(`https://musicbrainz.org/ws/2/recording?query=${query}&fmt=json`); |
| 26 | + const data = await response.json(); |
| 27 | + |
| 28 | + // Ensure the data is in the expected format |
| 29 | + if (!data.recordings || !Array.isArray(data.recordings)) { |
| 30 | + return json({ error: 'Invalid data format from MusicBrainz API' }, { status: 500 }); |
| 31 | + } |
| 32 | + |
| 33 | + const songs = data.recordings.map(recording => ({ |
| 34 | + title: recording.title, |
| 35 | + artist: recording['artist-credit']?.[0]?.name || 'Unknown artist', |
| 36 | + album: recording.releases?.[0]?.title || 'Unknown album', |
| 37 | + musicbrainz_id: recording.id, |
| 38 | + data: recording |
| 39 | + })); |
| 40 | + |
| 41 | + // Save the songs in the Songs collection |
| 42 | + const result = await db.collection('songs').insertMany(songs); |
| 43 | + const songIds = Object.values(result.insertedIds); |
| 44 | + |
| 45 | + // Cache the search query and results in the Searches collection |
| 46 | + await db.collection('searches').insertOne({ query, results: songIds, timestamp: new Date() }); |
| 47 | + |
| 48 | + return json({ songs }); |
| 49 | +} |
0 commit comments