Skip to content

Commit ee47ff3

Browse files
alakKevin CATHALYcoyotte508
authored
Add conversation API endpoint to get conversation (#698)
* Sorting conversation list in api response * Add new conversation endpoint in the api * only expose needed param in the API * Update src/routes/api/conversations/+server.ts Co-authored-by: Eliott C. <coyotte508@gmail.com> * linter * fix type --------- Co-authored-by: Kevin CATHALY <alakme@kevins-mbp.home> Co-authored-by: Eliott C. <coyotte508@gmail.com>
1 parent 9b5d65a commit ee47ff3

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { collections } from "$lib/server/database";
2+
import { authCondition } from "$lib/server/auth";
3+
import { z } from "zod";
4+
import { ObjectId } from "mongodb";
5+
6+
export async function GET({ locals, params }) {
7+
const id = z.string().parse(params.id);
8+
const convId = new ObjectId(id);
9+
10+
if (locals.user?._id || locals.sessionId) {
11+
const conv = await collections.conversations.findOne({
12+
_id: convId,
13+
...authCondition(locals),
14+
});
15+
16+
if (conv) {
17+
const res = {
18+
id: conv._id,
19+
title: conv.title,
20+
updatedAt: conv.updatedAt,
21+
modelId: conv.model,
22+
messages: conv.messages.map((message) => ({
23+
content: message.content,
24+
from: message.from,
25+
id: message.id,
26+
createdAt: message.createdAt,
27+
updatedAt: message.updatedAt,
28+
webSearch: message.webSearch,
29+
})),
30+
};
31+
return Response.json(res);
32+
} else {
33+
return Response.json({ message: "Conversation not found" }, { status: 404 });
34+
}
35+
} else {
36+
return Response.json({ message: "Must have session cookie" }, { status: 401 });
37+
}
38+
}

src/routes/api/conversations/+server.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,28 @@
11
import { collections } from "$lib/server/database";
22
import { authCondition } from "$lib/server/auth";
3+
import type { Conversation } from "$lib/types/Conversation";
34

45
export async function GET({ locals }) {
56
if (locals.user?._id || locals.sessionId) {
6-
const res = await collections.conversations
7+
const convs = await collections.conversations
78
.find({
89
...authCondition(locals),
910
})
11+
.project<Pick<Conversation, "_id" | "title" | "updatedAt" | "model">>({
12+
title: 1,
13+
updatedAt: 1,
14+
model: 1,
15+
})
16+
.sort({ updatedAt: -1 })
1017
.toArray();
1118

19+
const res = convs.map((conv) => ({
20+
id: conv._id,
21+
title: conv.title,
22+
updatedAt: conv.updatedAt,
23+
modelId: conv.model,
24+
}));
25+
1226
return Response.json(res);
1327
} else {
1428
return Response.json({ message: "Must have session cookie" }, { status: 401 });

0 commit comments

Comments
 (0)