-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
147 lines (125 loc) · 4.26 KB
/
index.js
File metadata and controls
147 lines (125 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import express, { json } from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
const app = express();
app.use(json());
app.use(bodyParser.json());
// Define the schema for a conversation
const conversationSchema = new mongoose.Schema({
conversationId: String,
user1: String,
user2: String,
messages: [
{
user: String,
message: String,
createdAt: { type: Date, default: Date.now },
},
],
});
// Create a model from the schema
const Conversation = mongoose.model("Conversation", conversationSchema);
// Connect to MongoDB
mongoose.connect(
"mongodb+srv://Hirez:PHTM@hirez.g3zvonv.mongodb.net/?retryWrites=true&w=majority"
);
app.post("/api/create-conversation", async (req, res) => {
const { user1, user2 } = req.body;
const conversationId = `${user1}-${user2}`;
const conversationId2 = `${user2}-${user1}`;
// Check if conversation already exists
const existingConversation = await Conversation.findOne({
$or: [{ conversationId }, { conversationId: conversationId2 }],
});
if (existingConversation) {
// If conversation already exists, return existing conversation's MongoDB _id
res.send({ _id: existingConversation._id });
} else {
// If conversation does not exist, create new conversation and return new conversation's MongoDB _id
const conversation = new Conversation({
conversationId,
user1,
user2,
messages: [],
});
await conversation.save();
res.send({ _id: conversation._id });
}
});
app.post("/api/send-message", async (req, res) => {
const { conversationId, user, message } = req.body;
const conversation = await Conversation.findById(conversationId);
if (conversation) {
conversation.messages.push({ user, message: message });
await conversation.save();
res.send({ status: "Message sent" });
} else {
res.send({ status: "Conversation not found" });
}
});
app.get("/api/fetch-messages/:conversationId", async (req, res) => {
const { conversationId } = req.params;
const conversation = await Conversation.findById(conversationId);
if (conversation) {
// Fetch only the last 10 messages
const messages = conversation.messages.slice(-10);
res.send(messages);
} else {
res.send({ status: "Conversation not found" });
}
});
app.get("/api/fetch-conversations/:userId", async (req, res) => {
const { userId } = req.params;
const conversations = await Conversation.find({
$or: [{ user1: userId }, { user2: userId }],
});
if (conversations) {
// Send the conversationIds along with the last message of each conversation
const conversationData = conversations.map((conversation) => {
return {
conversationId: conversation._id,
lastMessage: conversation.messages.slice(-1)[0],
};
});
res.send(conversationData);
} else {
res.send({ status: "No conversations found" });
}
});
// requset should be like this
// {
// "users": ["user1", "user2", "user3"],
// "message": "Hello, this is a message from AI2"
// }
app.post("/api/message-from-ai", async (req, res) => {
const { users, message } = req.body;
const aiId = "662926a964eb192f681f3c41";
let results = [];
for (let i = 0; i < users.length; i++) {
const user = users[i];
const conversationId = `${aiId}-${user}`;
const conversationId2 = `${user}-${aiId}`;
// Check if conversation already exists
const existingConversation = await Conversation.findOne({
$or: [{ conversationId }, { conversationId: conversationId2 }],
});
if (existingConversation) {
// If conversation already exists, return existing conversation's MongoDB _id
existingConversation.messages.push({ aiId, message });
const result = await existingConversation.save();
results.push({ status: "Message sent", result });
} else {
// If conversation does not exist, create new conversation and return new conversation's MongoDB _id
const conversation = new Conversation({
conversationId,
aiId,
user,
messages: [{ aiId, message }],
});
const result = await conversation.save();
results.push({ status: "Message sent", result });
}
}
res.send(results);
});
app.listen(3001, () => console.log("Server running on port 3001"));