Files
infohliadka/pages/api/search/index.ts
2024-06-04 15:27:11 +02:00

32 lines
939 B
TypeScript

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()
}
}