Files
brainstorming/server/api/analysis/index.post.ts
Alejandro Martinez 08846c9c63 fix: lazy DB initialization — useDb() called inside handlers, not at import
useRuntimeConfig() and better-sqlite3 were being called at module
top-level, which crashes during Nitro server startup. Now all DB
access is lazy via useDb(), and auth uses process.env directly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 15:36:17 +02:00

46 lines
1.6 KiB
TypeScript

import { useDb } from '../../utils/db'
import { requireAdmin } from '../../utils/auth'
export default defineEventHandler(async (event) => {
requireAdmin(event)
const db = useDb()
const ideas = db.prepare('SELECT text, category FROM ideas WHERE hidden = 0').all() as any[]
if (ideas.length < 3) {
throw createError({ statusCode: 400, statusMessage: 'Need at least 3 ideas' })
}
const { apiKey } = await readBody(event)
if (!apiKey) {
throw createError({ statusCode: 400, statusMessage: 'API key required' })
}
const prompt = `Analiza las siguientes ideas de automatización propuestas por un equipo de ingeniería:
${ideas.map((i: any) => `- [${i.category}]: ${i.text}`).join('\n')}
Por favor, genera un resumen ejecutivo en formato JSON con:
1. "topFrictionPoints": Los 3 problemas más recurrentes.
2. "quickWins": Automatizaciones fáciles de implementar con alto impacto.
3. "strategicAdvice": Recomendación sobre qué priorizar.
Responde SOLO con el JSON.`
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { responseMimeType: 'application/json' },
}),
},
)
if (!response.ok) {
throw createError({ statusCode: 502, statusMessage: 'AI API failed' })
}
const data = await response.json()
return JSON.parse(data.candidates[0].content.parts[0].text)
})