working team update/create (still need enroll)
This commit is contained in:
81
src/app/routes/api/spotify/search.ts
Normal file
81
src/app/routes/api/spotify/search.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { createServerFileRoute } from '@tanstack/react-start/server'
|
||||
|
||||
// Function to get Client Credentials access token
|
||||
async function getClientCredentialsToken(): Promise<string> {
|
||||
const clientId = process.env.VITE_SPOTIFY_CLIENT_ID
|
||||
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error('Missing Spotify client credentials')
|
||||
}
|
||||
|
||||
const response = await fetch('https://accounts.spotify.com/api/token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Authorization': `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
|
||||
},
|
||||
body: 'grant_type=client_credentials',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to get Spotify access token')
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return data.access_token
|
||||
}
|
||||
|
||||
export const ServerRoute = createServerFileRoute('/api/spotify/search').methods({
|
||||
GET: async ({ request }: { request: Request }) => {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const query = url.searchParams.get('q')
|
||||
|
||||
if (!query) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Query parameter q is required' }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Get client credentials access token
|
||||
const accessToken = await getClientCredentialsToken()
|
||||
|
||||
// Search using Spotify API directly
|
||||
const searchUrl = `https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track&limit=20`
|
||||
|
||||
const searchResponse = await fetch(searchUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!searchResponse.ok) {
|
||||
throw new Error('Spotify search request failed')
|
||||
}
|
||||
|
||||
const searchResult = await searchResponse.json()
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ tracks: searchResult.tracks.items }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Search error:', error)
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Search failed', details: error instanceof Error ? error.message : 'Unknown error' }),
|
||||
{
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user