CHAINR / backend /src /controllers /conversationController.js
chainr-ai's picture
Upload 8536 files
4888678 verified
const Conversation = require('../models/Conversation');
const Message = require('../models/Message');
const Joi = require('joi');
// Validation schemas
const createConversationSchema = Joi.object({
title: Joi.string().min(1).max(100).required()
});
const updateConversationSchema = Joi.object({
title: Joi.string().min(1).max(100),
isArchived: Joi.boolean(),
tags: Joi.array().items(Joi.string().trim())
});
// Create new conversation
exports.createConversation = async (req, res) => {
try {
// Validate input
const { error } = createConversationSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
const { title } = req.body;
const userId = req.userId;
const conversation = new Conversation({
title,
userId
});
await conversation.save();
res.status(201).json({
message: 'Conversation created successfully',
conversation
});
} catch (error) {
console.error('Create conversation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Get user conversations
exports.getConversations = async (req, res) => {
try {
const { page = 1, limit = 20, search, archived } = req.query;
const userId = req.userId;
// Build query
const query = { userId };
if (archived !== undefined) {
query.isArchived = archived === 'true';
}
if (search) {
query.title = { $regex: search, $options: 'i' };
}
// Get conversations with pagination
const conversations = await Conversation.find(query)
.sort({ lastMessageAt: -1 })
.limit(limit * 1)
.skip((page - 1) * limit);
const total = await Conversation.countDocuments(query);
res.json({
conversations,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit)
}
});
} catch (error) {
console.error('Get conversations error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Get single conversation
exports.getConversation = async (req, res) => {
try {
const { conversationId } = req.params;
const userId = req.userId;
const conversation = await Conversation.findOne({
_id: conversationId,
userId
});
if (!conversation) {
return res.status(404).json({ error: 'Conversation not found' });
}
res.json({ conversation });
} catch (error) {
console.error('Get conversation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Update conversation
exports.updateConversation = async (req, res) => {
try {
// Validate input
const { error } = updateConversationSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
const { conversationId } = req.params;
const userId = req.userId;
const updates = req.body;
const conversation = await Conversation.findOneAndUpdate(
{ _id: conversationId, userId },
updates,
{ new: true, runValidators: true }
);
if (!conversation) {
return res.status(404).json({ error: 'Conversation not found' });
}
res.json({
message: 'Conversation updated successfully',
conversation
});
} catch (error) {
console.error('Update conversation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
// Delete conversation
exports.deleteConversation = async (req, res) => {
try {
const { conversationId } = req.params;
const userId = req.userId;
const conversation = await Conversation.findOneAndDelete({
_id: conversationId,
userId
});
if (!conversation) {
return res.status(404).json({ error: 'Conversation not found' });
}
// Delete all messages in the conversation
await Message.deleteMany({ conversationId });
res.json({ message: 'Conversation deleted successfully' });
} catch (error) {
console.error('Delete conversation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
};