Nexus/src/server/routes/conversations.ts

94 lines
2.4 KiB
TypeScript

import express from 'express';
import prisma from '../../db/prisma';
const router = express.Router();
// Get conversations for an agent or Just Chat
router.get('/', async (req, res) => {
try {
const { agentId, isJustChat } = req.query;
let user = await prisma.user.findUnique({ where: { email: 'local@localhost' } });
if (!user) {
user = await prisma.user.create({ data: { email: 'local@localhost', password: 'local', name: 'Local User' } });
}
const where: any = { userId: user.id };
if (isJustChat === 'true') {
where.agentId = null;
} else if (agentId) {
where.agentId = agentId;
}
const conversations = await prisma.conversation.findMany({
where,
include: {
messages: {
orderBy: { createdAt: 'asc' }
},
agent: true
},
orderBy: { updatedAt: 'desc' }
});
res.json({ success: true, data: conversations });
} catch (err) {
res.status(500).json({ success: false, error: (err as any).message });
}
});
// Get active conversation for agent/justChat
router.get('/active', async (req, res) => {
try {
const { agentId, isJustChat } = req.query;
let user = await prisma.user.findUnique({ where: { email: 'local@localhost' } });
if (!user) {
user = await prisma.user.create({ data: { email: 'local@localhost', password: 'local', name: 'Local User' } });
}
const where: any = { userId: user.id };
if (isJustChat === 'true') {
where.agentId = null;
} else if (agentId) {
where.agentId = agentId;
}
// Get most recent conversation
const conversation = await prisma.conversation.findFirst({
where,
include: {
messages: {
orderBy: { createdAt: 'asc' }
}
},
orderBy: { updatedAt: 'desc' }
});
res.json({ success: true, data: conversation });
} catch (err) {
res.status(500).json({ success: false, error: (err as any).message });
}
});
// Get messages for a specific conversation
router.get('/:conversationId/messages', async (req, res) => {
try {
const { conversationId } = req.params;
const messages = await prisma.message.findMany({
where: { conversationId },
orderBy: { createdAt: 'asc' }
});
res.json({ success: true, data: messages });
} catch (err) {
res.status(500).json({ success: false, error: (err as any).message });
}
});
export default router;