Files
infohliadka/pages/api/domains/risky.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

55 lines
1.9 KiB
TypeScript

import type { NextApiRequest, NextApiResponse } from 'next'
import { db, schema } from '../../../lib/db/connection'
import { eq, gte, desc, count, sql } from 'drizzle-orm'
interface RiskyDomain {
domain: string
source_count: number
avg_risk_level: number
max_risk_level: number
categories: string[]
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<RiskyDomain[] | { error: string }>
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
const { limit = '20' } = req.query
try {
const riskyDomainsResult = await db
.select({
domain: schema.sources.domain,
sourceCount: count(),
avgRiskLevel: sql<number>`AVG(${schema.sources.riskLevel})`,
maxRiskLevel: sql<number>`MAX(${schema.sources.riskLevel})`,
categories: sql<string>`string_agg(DISTINCT ${schema.categories.name}, ',')`
})
.from(schema.sources)
.leftJoin(schema.sourceCategories, eq(schema.sources.id, schema.sourceCategories.sourceId))
.leftJoin(schema.categories, eq(schema.sourceCategories.categoryId, schema.categories.id))
.where(eq(schema.sources.status, 'verified'))
.groupBy(schema.sources.domain)
.having(gte(sql`AVG(${schema.sources.riskLevel})`, 3))
.orderBy(desc(sql`AVG(${schema.sources.riskLevel})`), desc(count()))
.limit(parseInt(limit as string))
const riskyDomains: RiskyDomain[] = riskyDomainsResult.map(row => ({
domain: row.domain,
source_count: row.sourceCount,
avg_risk_level: Math.round(row.avgRiskLevel * 10) / 10,
max_risk_level: row.maxRiskLevel,
categories: row.categories ? row.categories.split(',').filter(Boolean) : []
}))
return res.status(200).json(riskyDomains)
} catch (error) {
console.error('Database error:', error)
return res.status(500).json({ error: 'Internal server error' })
}
}