deckhearth/pages/api/cards/search.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

import { sql } from '@vercel/postgres';
export default async function handler(req, res) {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Handle preflight requests
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { q = '', limit = 20 } = req.query;
let result;
if (q.trim()) {
// Search by name
result = await sql`
SELECT id, name, set_name, rarity, card_type, image_url, market_price, game
FROM cards
WHERE name ILIKE ${`%${q}%`}
ORDER BY name
LIMIT ${parseInt(limit)}
`;
} else {
// Return all cards if no search query
result = await sql`
SELECT id, name, set_name, rarity, card_type, image_url, market_price, game
FROM cards
ORDER BY name
LIMIT ${parseInt(limit)}
`;
}
res.status(200).json(result.rows);
} catch (error) {
console.error('Error searching cards:', error);
res.status(500).json({ error: 'Internal server error' });
}
}