70 lines
2.4 KiB
JavaScript
70 lines
2.4 KiB
JavaScript
const DBName = "EMI_SOCIAL";
|
|
|
|
const chatDB = (DB) => {
|
|
DB.chatMessagesCol = DB.db.db(DBName).collection("chat_messages");
|
|
DB.chatMessagesCol.createIndex({ createdAt: -1 }).catch(console.error);
|
|
|
|
DB.addChatMessage = async ({ senderId, senderProfileId, senderName, text, sourceLang }) => {
|
|
const safeText = (text || "").trim();
|
|
if (!safeText) return false;
|
|
const message = {
|
|
senderId: senderId ? senderId + "" : "",
|
|
senderProfileId: senderProfileId ? senderProfileId + "" : "",
|
|
senderName: senderName || "Anonymous",
|
|
text: safeText,
|
|
sourceLang: sourceLang || "en",
|
|
translations: {},
|
|
createdAt: new Date(),
|
|
};
|
|
const result = await DB.chatMessagesCol.insertOne(message).catch((err) => {
|
|
console.log(err);
|
|
return false;
|
|
});
|
|
if (!result || !result.insertedId) return false;
|
|
return {
|
|
...message,
|
|
_id: result.insertedId,
|
|
};
|
|
};
|
|
|
|
DB.getChatParticipants = async () => {
|
|
return DB.chatMessagesCol.distinct("senderProfileId").catch((err) => {
|
|
console.log(err);
|
|
return [];
|
|
});
|
|
};
|
|
|
|
DB.getRecentChatMessages = async (limit = 100) => {
|
|
const safeLimit = Math.min(Math.max(parseInt(limit, 10) || 100, 1), 200);
|
|
const messages = await DB.chatMessagesCol.find({})
|
|
.sort({ createdAt: -1 })
|
|
.limit(safeLimit)
|
|
.toArray()
|
|
.catch((err) => {
|
|
console.log(err);
|
|
return [];
|
|
});
|
|
return messages.reverse();
|
|
};
|
|
|
|
DB.setChatMessageTranslation = async ({ messageId, targetLang, text, provider, model }) => {
|
|
if (!messageId || !targetLang || !text) return false;
|
|
const _id = typeof messageId === "string" ? DB.ObjectID(messageId) : messageId;
|
|
const fieldBase = `translations.${targetLang}`;
|
|
const update = {
|
|
$set: {
|
|
[`${fieldBase}.text`]: text,
|
|
[`${fieldBase}.provider`]: provider || "openai",
|
|
[`${fieldBase}.model`]: model || "",
|
|
[`${fieldBase}.updatedAt`]: new Date(),
|
|
},
|
|
};
|
|
return DB.chatMessagesCol.updateOne({ _id }, update).catch((err) => {
|
|
console.log(err);
|
|
return false;
|
|
});
|
|
};
|
|
};
|
|
|
|
module.exports = chatDB;
|