feat: multiple sessions per story with streaming AI responses
This commit is contained in:
+116
-13
@@ -310,24 +310,102 @@ app.delete("/api/stories/:id", requireAuth, async (req, res) => {
|
||||
|
||||
// ============ GAME SESSIONS ROUTES ============
|
||||
|
||||
// Получить сессию игры
|
||||
// Получить список сессий для истории
|
||||
app.get("/api/sessions/:storyId", requireAuth, async (req, res) => {
|
||||
try {
|
||||
const sessions = db.collection("game_sessions");
|
||||
const userSessions = await sessions
|
||||
.find({
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
})
|
||||
.sort({ updatedAt: -1 })
|
||||
.toArray();
|
||||
|
||||
// Возвращаем список с базовой инфой (без полных сообщений)
|
||||
const sessionsList = userSessions.map((s) => ({
|
||||
id: s._id.toString(),
|
||||
name: s.name || "Сессия",
|
||||
messagesCount: s.messages?.length || 0,
|
||||
createdAt: s.createdAt,
|
||||
updatedAt: s.updatedAt,
|
||||
}));
|
||||
|
||||
res.json(sessionsList);
|
||||
} catch (error) {
|
||||
console.error("Get sessions list error:", error);
|
||||
res.status(500).json({ error: "Failed to get sessions" });
|
||||
}
|
||||
});
|
||||
|
||||
// Получить конкретную сессию
|
||||
app.get("/api/sessions/:storyId/:sessionId", requireAuth, async (req, res) => {
|
||||
try {
|
||||
const sessions = db.collection("game_sessions");
|
||||
|
||||
const session = await sessions.findOne({
|
||||
_id: new ObjectId(req.params.sessionId),
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
});
|
||||
|
||||
res.json(session);
|
||||
if (!session) {
|
||||
return res.status(404).json({ error: "Session not found" });
|
||||
}
|
||||
|
||||
res.json({ ...session, id: session._id.toString() });
|
||||
} catch (error) {
|
||||
console.error("Get session error:", error);
|
||||
res.status(500).json({ error: "Failed to get session" });
|
||||
}
|
||||
});
|
||||
|
||||
// Сохранить сессию игры
|
||||
// Создать новую сессию
|
||||
app.post("/api/sessions/:storyId", requireAuth, async (req, res) => {
|
||||
try {
|
||||
const sessions = db.collection("game_sessions");
|
||||
|
||||
// Считаем существующие сессии для нумерации
|
||||
const existingCount = await sessions.countDocuments({
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
});
|
||||
|
||||
const sessionData = {
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
name: req.body.name || `Сессия ${existingCount + 1}`,
|
||||
playerId: req.body.playerId || null,
|
||||
messages: [],
|
||||
currentState: {
|
||||
location: "start",
|
||||
health: 100,
|
||||
inventory: [],
|
||||
questProgress: {},
|
||||
},
|
||||
storySummary: "",
|
||||
keyEvents: [],
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
const result = await sessions.insertOne(sessionData);
|
||||
|
||||
res.json({
|
||||
id: result.insertedId.toString(),
|
||||
name: sessionData.name,
|
||||
messagesCount: 0,
|
||||
createdAt: sessionData.createdAt,
|
||||
updatedAt: sessionData.updatedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Create session error:", error);
|
||||
res.status(500).json({ error: "Failed to create session" });
|
||||
}
|
||||
});
|
||||
|
||||
// Обновить сессию
|
||||
app.put("/api/sessions/:storyId/:sessionId", requireAuth, async (req, res) => {
|
||||
try {
|
||||
const sessions = db.collection("game_sessions");
|
||||
|
||||
@@ -343,30 +421,55 @@ app.post("/api/sessions/:storyId", requireAuth, async (req, res) => {
|
||||
const sessionData = {
|
||||
...bodyWithoutMeta,
|
||||
messages,
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
await sessions.updateOne(
|
||||
const result = await sessions.updateOne(
|
||||
{
|
||||
_id: new ObjectId(req.params.sessionId),
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
},
|
||||
{
|
||||
$set: sessionData,
|
||||
$setOnInsert: { createdAt: new Date() },
|
||||
},
|
||||
{ upsert: true },
|
||||
{ $set: sessionData },
|
||||
);
|
||||
|
||||
if (result.matchedCount === 0) {
|
||||
return res.status(404).json({ error: "Session not found" });
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Save session error:", error);
|
||||
res.status(500).json({ error: "Failed to save session" });
|
||||
console.error("Update session error:", error);
|
||||
res.status(500).json({ error: "Failed to update session" });
|
||||
}
|
||||
});
|
||||
|
||||
// Удалить сессию
|
||||
app.delete(
|
||||
"/api/sessions/:storyId/:sessionId",
|
||||
requireAuth,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const sessions = db.collection("game_sessions");
|
||||
|
||||
const result = await sessions.deleteOne({
|
||||
_id: new ObjectId(req.params.sessionId),
|
||||
storyId: req.params.storyId,
|
||||
userId: req.session.userId,
|
||||
});
|
||||
|
||||
if (result.deletedCount === 0) {
|
||||
return res.status(404).json({ error: "Session not found" });
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Delete session error:", error);
|
||||
res.status(500).json({ error: "Failed to delete session" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ============ PLAYER CHARACTERS ROUTES ============
|
||||
|
||||
// Получить всех персонажей пользователя
|
||||
|
||||
Reference in New Issue
Block a user