NeahFront7/app/api/news/route.ts
2025-04-13 23:14:00 +02:00

137 lines
3.4 KiB
TypeScript

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');
}
// Remove any protocol and trailing slashes
return host.replace(/^https?:\/\//, '').replace(/\/$/, '');
}
// Create connection configuration
const dbConfig = {
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
host: cleanDatabaseHost(process.env.DB_HOST),
database: process.env.DB_NAME,
port: 5432, // Default PostgreSQL port
ssl: {
rejectUnauthorized: false
}
};
// Create a new pool using the configuration
const pool = new Pool(dbConfig);
// Mock data for development
const MOCK_NEWS = [
{
id: 1,
title: "New Project Management Features Released",
url: "#",
date: "2024-03-20",
source: "Internal",
description: "New features added to improve project management workflow",
category: "Update",
sentiment: { score: null, label: null },
symbols: null,
symbol: null
},
{
id: 2,
title: "Team Meeting Schedule Changes",
url: "#",
date: "2024-03-19",
source: "Internal",
description: "Updates to the team meeting schedule",
category: "Announcement",
sentiment: { score: null, label: null },
symbols: null,
symbol: null
},
{
id: 3,
title: "Upcoming Training Sessions",
url: "#",
date: "2024-03-18",
source: "Internal",
description: "Schedule for upcoming training sessions",
category: "Training",
sentiment: { score: null, label: null },
symbols: null,
symbol: null
}
];
export async function GET() {
try {
console.log('Attempting database connection with config:', {
user: dbConfig.user,
host: dbConfig.host,
database: dbConfig.database,
// Excluding password for security
});
// Connect to the database
const client = await pool.connect();
console.log('Successfully connected to database');
try {
console.log('Executing news query...');
// Query the news table for the latest 10 news items
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(`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 });
} finally {
// Release the client back to the pool
client.release();
console.log('Database client released');
}
} catch (error) {
console.error('Database error:', error);
return NextResponse.json(
{
error: 'Failed to fetch news',
details: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
}
}