60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { auth } from '@/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { EmbeddingService } from '@/lib/ai/services/embedding.service'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await auth()
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const userId = session.user.id
|
|
|
|
// Fetch all notes for the user
|
|
const notes = await prisma.note.findMany({
|
|
where: { userId, trashedAt: null },
|
|
select: { id: true, title: true, content: true }
|
|
})
|
|
|
|
const embeddingService = new EmbeddingService()
|
|
let processedCount = 0
|
|
|
|
// Process in small batches to avoid timeouts if possible
|
|
// Note: In a real production app, this should be a background job
|
|
for (const note of notes) {
|
|
try {
|
|
const textToEmbed = `${note.title || ''}\n${note.content}`
|
|
if (textToEmbed.trim()) {
|
|
const embedding = await embeddingService.generateEmbedding(textToEmbed)
|
|
|
|
await prisma.noteEmbedding.upsert({
|
|
where: { noteId: note.id },
|
|
update: { embedding: JSON.stringify(embedding) },
|
|
create: {
|
|
noteId: note.id,
|
|
embedding: JSON.stringify(embedding)
|
|
}
|
|
})
|
|
processedCount++
|
|
}
|
|
} catch (err) {
|
|
console.error(`Failed to reindex note ${note.id}:`, err)
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
count: processedCount,
|
|
total: notes.length
|
|
})
|
|
} catch (error) {
|
|
console.error('Reindex error:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Failed to reindex notes' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|