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
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next"
|
||||
import sqlite3 from "sqlite3"
|
||||
import path from "path"
|
||||
import { db, schema } from '../../../lib/db/connection'
|
||||
import { eq, and, or, like, gte, lte, desc, count, sql } from 'drizzle-orm'
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" })
|
||||
@@ -15,80 +15,113 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
limit = '20'
|
||||
} = req.query
|
||||
|
||||
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
|
||||
const db = new sqlite3.Database(dbPath)
|
||||
|
||||
try {
|
||||
let whereConditions = ["s.status = ?"]
|
||||
let params: any[] = [status]
|
||||
let whereConditions = [eq(schema.sources.status, status as string)]
|
||||
|
||||
if (q) {
|
||||
whereConditions.push("(s.domain LIKE ? OR s.title LIKE ? OR s.description LIKE ?)")
|
||||
params.push(`%${q}%`, `%${q}%`, `%${q}%`)
|
||||
}
|
||||
|
||||
if (category) {
|
||||
whereConditions.push("EXISTS (SELECT 1 FROM source_categories sc JOIN categories c ON sc.category_id = c.id WHERE sc.source_id = s.id AND c.name = ?)")
|
||||
params.push(category)
|
||||
whereConditions.push(
|
||||
or(
|
||||
like(schema.sources.domain, `%${q}%`),
|
||||
like(schema.sources.title, `%${q}%`),
|
||||
like(schema.sources.description, `%${q}%`)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
if (risk_level_min) {
|
||||
whereConditions.push("s.risk_level >= ?")
|
||||
params.push(parseInt(risk_level_min as string))
|
||||
whereConditions.push(gte(schema.sources.riskLevel, parseInt(risk_level_min as string)))
|
||||
}
|
||||
|
||||
if (risk_level_max) {
|
||||
whereConditions.push("s.risk_level <= ?")
|
||||
params.push(parseInt(risk_level_max as string))
|
||||
whereConditions.push(lte(schema.sources.riskLevel, parseInt(risk_level_max as string)))
|
||||
}
|
||||
|
||||
const offset = (parseInt(page as string) - 1) * parseInt(limit as string)
|
||||
const limitInt = parseInt(limit as string)
|
||||
|
||||
const query = `
|
||||
SELECT s.*, GROUP_CONCAT(c.name) as categories,
|
||||
COUNT(*) OVER() as total_count
|
||||
FROM sources s
|
||||
LEFT JOIN source_categories sc ON s.id = sc.source_id
|
||||
LEFT JOIN categories c ON sc.category_id = c.id
|
||||
WHERE ${whereConditions.join(' AND ')}
|
||||
GROUP BY s.id
|
||||
ORDER BY s.risk_level DESC, s.created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`
|
||||
|
||||
params.push(parseInt(limit as string), offset)
|
||||
|
||||
const results = await new Promise<any[]>((resolve, reject) => {
|
||||
db.all(query, params, (err, rows) => {
|
||||
if (err) reject(err)
|
||||
else resolve(rows)
|
||||
// Build the base query
|
||||
let query = db
|
||||
.select({
|
||||
id: schema.sources.id,
|
||||
domain: schema.sources.domain,
|
||||
title: schema.sources.title,
|
||||
riskLevel: schema.sources.riskLevel,
|
||||
description: schema.sources.description,
|
||||
createdAt: schema.sources.createdAt,
|
||||
categories: sql<string>`string_agg(${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(and(...whereConditions))
|
||||
.groupBy(schema.sources.id, schema.sources.domain, schema.sources.title, schema.sources.riskLevel, schema.sources.description, schema.sources.createdAt)
|
||||
.orderBy(desc(schema.sources.riskLevel), desc(schema.sources.createdAt))
|
||||
.limit(limitInt)
|
||||
.offset(offset)
|
||||
|
||||
const total = results.length > 0 ? results[0].total_count : 0
|
||||
const totalPages = Math.ceil(total / parseInt(limit as string))
|
||||
// Apply category filter if provided
|
||||
if (category) {
|
||||
query = db
|
||||
.select({
|
||||
id: schema.sources.id,
|
||||
domain: schema.sources.domain,
|
||||
title: schema.sources.title,
|
||||
riskLevel: schema.sources.riskLevel,
|
||||
description: schema.sources.description,
|
||||
createdAt: schema.sources.createdAt,
|
||||
categories: sql<string>`string_agg(${schema.categories.name}, ',')`
|
||||
})
|
||||
.from(schema.sources)
|
||||
.innerJoin(schema.sourceCategories, eq(schema.sources.id, schema.sourceCategories.sourceId))
|
||||
.innerJoin(schema.categories, eq(schema.sourceCategories.categoryId, schema.categories.id))
|
||||
.where(and(...whereConditions, eq(schema.categories.name, category as string)))
|
||||
.groupBy(schema.sources.id, schema.sources.domain, schema.sources.title, schema.sources.riskLevel, schema.sources.description, schema.sources.createdAt)
|
||||
.orderBy(desc(schema.sources.riskLevel), desc(schema.sources.createdAt))
|
||||
.limit(limitInt)
|
||||
.offset(offset)
|
||||
}
|
||||
|
||||
const results = await query
|
||||
|
||||
// Get total count for pagination
|
||||
let countQuery = db
|
||||
.select({ count: count() })
|
||||
.from(schema.sources)
|
||||
.where(and(...whereConditions))
|
||||
|
||||
if (category) {
|
||||
countQuery = db
|
||||
.select({ count: count() })
|
||||
.from(schema.sources)
|
||||
.innerJoin(schema.sourceCategories, eq(schema.sources.id, schema.sourceCategories.sourceId))
|
||||
.innerJoin(schema.categories, eq(schema.sourceCategories.categoryId, schema.categories.id))
|
||||
.where(and(...whereConditions, eq(schema.categories.name, category as string)))
|
||||
}
|
||||
|
||||
const [totalResult] = await countQuery
|
||||
const total = totalResult.count
|
||||
const totalPages = Math.ceil(total / limitInt)
|
||||
|
||||
res.json({
|
||||
results: results.map(row => ({
|
||||
id: row.id,
|
||||
domain: row.domain,
|
||||
title: row.title,
|
||||
risk_level: row.risk_level,
|
||||
categories: row.categories ? row.categories.split(',') : [],
|
||||
risk_level: row.riskLevel,
|
||||
categories: row.categories ? row.categories.split(',').filter(Boolean) : [],
|
||||
description: row.description,
|
||||
created_at: row.created_at
|
||||
created_at: row.createdAt
|
||||
})),
|
||||
pagination: {
|
||||
page: parseInt(page as string),
|
||||
limit: parseInt(limit as string),
|
||||
limit: limitInt,
|
||||
total,
|
||||
totalPages
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Search error:', error)
|
||||
res.status(500).json({ error: "Search failed" })
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user