Files
infohliadka/pages/api/stats.ts
Lukas Davidovic 860070a302 migrate from SQLite to PostgreSQL with Drizzle ORM
- Updated all packages to latest versions (React 19, Next.js 14.2.32)
- Replaced sqlite3 with pg and drizzle-orm dependencies
- Created complete PostgreSQL schema with relationships and indexes
- Migrated all API endpoints from SQLite to Drizzle queries
- Added database seeding with sample data
- Updated authentication to use bcrypt instead of pbkdf2
- Configured connection pooling for PostgreSQL
- Updated app version to 1.0.0
- All endpoints tested and working correctly
2025-09-06 12:56:33 +02:00

93 lines
2.9 KiB
TypeScript

import type { NextApiRequest, NextApiResponse } from 'next'
import { db, schema } from '../../lib/db/connection'
import { eq, gte, count, desc, sql } from 'drizzle-orm'
interface PublicStats {
total_sources: number
high_risk_sources: number
categories_breakdown: { [key: string]: number }
recent_additions: number
top_domains: { domain: string; count: number; risk_level: number }[]
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<PublicStats | { error: string }>
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
try {
// Get basic counts
const [totalSourcesResult] = await db
.select({ count: count() })
.from(schema.sources)
.where(eq(schema.sources.status, 'verified'))
const [highRiskSourcesResult] = await db
.select({ count: count() })
.from(schema.sources)
.where(
sql`${schema.sources.status} = 'verified' AND ${schema.sources.riskLevel} >= 4`
)
const thirtyDaysAgo = new Date()
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
const [recentAdditionsResult] = await db
.select({ count: count() })
.from(schema.sources)
.where(gte(schema.sources.createdAt, thirtyDaysAgo))
// Get categories breakdown
const categoriesBreakdownResult = await db
.select({
name: schema.categories.name,
count: count()
})
.from(schema.categories)
.innerJoin(schema.sourceCategories, eq(schema.categories.id, schema.sourceCategories.categoryId))
.innerJoin(schema.sources, eq(schema.sourceCategories.sourceId, schema.sources.id))
.where(eq(schema.sources.status, 'verified'))
.groupBy(schema.categories.id, schema.categories.name)
const categoriesBreakdown: { [key: string]: number } = {}
categoriesBreakdownResult.forEach(row => {
categoriesBreakdown[row.name] = row.count
})
// Get top risky domains
const topDomainsResult = await db
.select({
domain: schema.sources.domain,
count: count(),
avgRisk: sql<number>`AVG(${schema.sources.riskLevel})`
})
.from(schema.sources)
.where(eq(schema.sources.status, 'verified'))
.groupBy(schema.sources.domain)
.orderBy(desc(sql`AVG(${schema.sources.riskLevel})`), desc(count()))
.limit(10)
const topDomains = topDomainsResult.map(row => ({
domain: row.domain,
count: row.count,
risk_level: Math.round(row.avgRisk * 10) / 10
}))
const stats: PublicStats = {
total_sources: totalSourcesResult.count,
high_risk_sources: highRiskSourcesResult.count,
categories_breakdown: categoriesBreakdown,
recent_additions: recentAdditionsResult.count,
top_domains: topDomains
}
return res.status(200).json(stats)
} catch (error) {
console.error('Database error:', error)
return res.status(500).json({ error: 'Internal server error' })
}
}