import { NextResponse } from 'next/server'; import { Pool } from 'pg'; // Function to clean database host URL function cleanDatabaseHost(host: string | undefined): string { if (!host) { throw new Error('Database host is not defined'); } return host.replace(/^https?:\/\//, ''); } // Create a new pool using the environment variables const pool = new Pool({ user: process.env.DB_USER, password: process.env.DB_PASSWORD, host: cleanDatabaseHost(process.env.DB_HOST), database: process.env.DB_NAME, ssl: { rejectUnauthorized: false // Required for some cloud databases } }); export async function GET() { try { // Log connection attempt console.log('Attempting database connection with config:', { user: process.env.DB_USER, host: process.env.DB_HOST, database: process.env.DB_NAME, hasPassword: !!process.env.DB_PASSWORD }); // Connect to the database const client = await pool.connect(); console.log('Successfully connected to database'); try { // Query the news table for the latest 10 news items console.log('Executing news query...'); const result = await client.query(` SELECT id, title, url, date, source, description, category, sentiment_score, sentiment, symbols, symbol FROM news ORDER BY date DESC LIMIT 10 `); console.log(`Query completed. Found ${result.rows.length} news items.`); // Format the response const news = result.rows.map(row => ({ id: row.id, title: row.title, url: row.url, date: row.date, source: row.source, description: row.description, category: row.category, sentiment: { score: row.sentiment_score, label: row.sentiment }, symbols: row.symbols, symbol: row.symbol })); return NextResponse.json({ news }); } catch (queryError: any) { console.error('Query error:', queryError); return NextResponse.json( { error: 'Database query failed: ' + (queryError?.message || 'Unknown error') }, { status: 500 } ); } finally { // Release the client back to the pool client.release(); console.log('Database client released'); } } catch (error: any) { console.error('Database connection error:', error); // Check if error is due to missing configuration if (!process.env.DB_USER || !process.env.DB_PASSWORD || !process.env.DB_HOST || !process.env.DB_NAME) { console.error('Missing database configuration:', { hasUser: !!process.env.DB_USER, hasPassword: !!process.env.DB_PASSWORD, hasHost: !!process.env.DB_HOST, hasDatabase: !!process.env.DB_NAME }); return NextResponse.json( { error: 'Database configuration is incomplete' }, { status: 500 } ); } return NextResponse.json( { error: 'Failed to connect to database: ' + (error?.message || 'Unknown error') }, { status: 500 } ); } }