72 lines
2.2 KiB
TypeScript
72 lines
2.2 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { Pool } from 'pg';
|
|
|
|
// Get database configuration from environment variables
|
|
const DB_HOST = process.env.DB_HOST || 'cube.governance-labs.com';
|
|
const DB_PORT = process.env.DB_PORT || '5432';
|
|
const DB_USER = process.env.DB_USER || 'alma';
|
|
const DB_PASSWORD = process.env.DB_PASSWORD;
|
|
const DB_NAME = process.env.DB_NAME || 'rivacube';
|
|
|
|
// Validate required environment variables
|
|
if (!DB_PASSWORD) {
|
|
console.error('DB_PASSWORD environment variable is not set');
|
|
throw new Error('Database password is not configured');
|
|
}
|
|
|
|
// Construct connection string from components
|
|
const connectionString = `postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`;
|
|
|
|
// Log the connection string (with password masked for security)
|
|
const maskedConnectionString = connectionString.replace(/\/\/[^:]+:[^@]+@/, '//***:***@');
|
|
console.log('Using connection string:', maskedConnectionString);
|
|
|
|
const pool = new Pool({
|
|
connectionString,
|
|
ssl: {
|
|
rejectUnauthorized: false // Required for some remote connections
|
|
},
|
|
// Add connection timeout
|
|
connectionTimeoutMillis: 5000,
|
|
// Add query timeout
|
|
query_timeout: 5000,
|
|
});
|
|
|
|
export async function GET() {
|
|
let client;
|
|
try {
|
|
console.log(`Attempting to connect to database at ${DB_HOST}:${DB_PORT}...`);
|
|
client = await pool.connect();
|
|
console.log('Database connection successful');
|
|
|
|
const result = await client.query(
|
|
`SELECT id, title, date, source, description, category, url
|
|
FROM news
|
|
ORDER BY date DESC
|
|
LIMIT 5`
|
|
);
|
|
|
|
console.log(`Successfully fetched ${result.rows.length} news articles`);
|
|
return NextResponse.json(result.rows);
|
|
} catch (error) {
|
|
console.error('Error in news API:', {
|
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
host: DB_HOST,
|
|
port: DB_PORT,
|
|
database: DB_NAME,
|
|
stack: error instanceof Error ? error.stack : undefined
|
|
});
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Failed to fetch news',
|
|
details: error instanceof Error ? error.message : 'Unknown error',
|
|
server: DB_HOST
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
} finally {
|
|
if (client) {
|
|
client.release();
|
|
}
|
|
}
|
|
}
|