73 lines
2.2 KiB
JavaScript
73 lines
2.2 KiB
JavaScript
import express from 'express';
|
|
import { query } from '../db/index.js';
|
|
import { authMiddleware } from '../middleware/auth.js';
|
|
import { asyncHandler, AppError } from '../middleware/errorHandler.js';
|
|
|
|
const router = express.Router();
|
|
|
|
// Search for shows/movies via TMDB with caching
|
|
router.get('/search', authMiddleware, asyncHandler(async (req, res) => {
|
|
const { q } = req.query;
|
|
|
|
if (!q || q.trim().length < 2) {
|
|
return res.json({ results: [] });
|
|
}
|
|
|
|
const searchQuery = q.trim();
|
|
|
|
// Check cache first
|
|
const cached = await query(
|
|
'SELECT response_data FROM tmdb_cache WHERE query = ? AND media_type = ? AND cached_at > DATE_SUB(NOW(), INTERVAL 7 DAY)',
|
|
[searchQuery, 'multi']
|
|
);
|
|
|
|
if (cached.length > 0) {
|
|
return res.json(JSON.parse(cached[0].response_data));
|
|
}
|
|
|
|
// Fetch from TMDB
|
|
const apiKey = process.env.TMDB_API_KEY;
|
|
if (!apiKey) {
|
|
throw new AppError('TMDB API key not configured', 500);
|
|
}
|
|
|
|
const fetch = (await import('node-fetch')).default;
|
|
const response = await fetch(
|
|
`https://api.themoviedb.org/3/search/multi?api_key=${apiKey}&query=${encodeURIComponent(searchQuery)}`
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
console.error('TMDB API error:', response.status, errorText);
|
|
throw new AppError(`TMDB API error: ${response.status}`, 500);
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
// Filter to only movies and TV shows
|
|
const filtered = data.results
|
|
.filter(item => item.media_type === 'movie' || item.media_type === 'tv')
|
|
.map(item => ({
|
|
id: item.id,
|
|
title: item.media_type === 'movie' ? item.title : item.name,
|
|
media_type: item.media_type,
|
|
poster_path: item.poster_path,
|
|
backdrop_path: item.backdrop_path,
|
|
release_date: item.release_date || item.first_air_date,
|
|
overview: item.overview
|
|
}))
|
|
.slice(0, 10);
|
|
|
|
const result = { results: filtered };
|
|
|
|
// Cache the result
|
|
await query(
|
|
'INSERT INTO tmdb_cache (query, media_type, response_data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE response_data = ?, cached_at = NOW()',
|
|
[searchQuery, 'multi', JSON.stringify(result), JSON.stringify(result)]
|
|
);
|
|
|
|
res.json(result);
|
|
}));
|
|
|
|
export default router;
|