search functionality

This commit is contained in:
2024-06-04 15:27:11 +02:00
parent cba0310536
commit 198a31fc5e

31
pages/api/search/index.ts Normal file
View File

@@ -0,0 +1,31 @@
import type { NextApiRequest, NextApiResponse } from "next"
import sqlite3 from "sqlite3"
import path from "path"
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" })
const { q } = req.query
if (!q) return res.status(400).json({ error: "Query required" })
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
const db = new sqlite3.Database(dbPath)
try {
const results = await new Promise<any[]>((resolve, reject) => {
db.all(
"SELECT * FROM sources WHERE domain LIKE ? OR title LIKE ? LIMIT 20",
[`%${q}%`, `%${q}%`],
(err, rows) => {
if (err) reject(err)
else resolve(rows)
}
)
})
res.json(results)
} catch (error) {
res.status(500).json({ error: "Database error" })
} finally {
db.close()
}
}