-
Notifications
You must be signed in to change notification settings - Fork 0
/
createAPIRouter.ts
96 lines (87 loc) · 2.77 KB
/
createAPIRouter.ts
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
import express from "express";
import { type Logger } from "pino";
import { addUserMessage } from "./chats/addUserMessage";
import { postDocumentBodySchema, postMessageBodySchema } from "./schemas";
import { ingestDocument } from "./documents/ingestDocument";
import { createAnonClient } from "./createAnonClient";
import { ChatsRow } from "./types";
export function createAPIRouter({ logger }: { logger: Logger }) {
// when mounted on the server, this router will be available at /api
const router = express.Router();
router.get("/health", (req, res) => {
res.status(200).send("ok");
});
// for vector store ingestion
router.post("/documents", express.json(), async (req, res, next) => {
// use a try-catch because not only dealing with supbabase errors
try {
const document = postDocumentBodySchema.parse(req.body);
await ingestDocument(document);
res.status(204).end();
} catch (error) {
logger.error({
message: "Document ingestion error",
error,
});
next(new Error("Document ingestion error"));
}
});
// for starting a chat - TODO: consider removing
router.post("/chats", express.json(), async (req, res, next) => {
const supabase = createAnonClient();
const insertChat = await supabase
.from("chats")
.insert({})
.select()
.single();
if (insertChat.error) {
logger.error({
message: "Chat creation error",
error: insertChat.error,
});
return next(new Error("Chat creation error"));
}
res.status(insertChat.status).send(JSON.stringify(insertChat.data));
});
// for sending a message - TODO: consider removing
router.post("/messages", express.json(), async (req, res, next) => {
const supabase = createAnonClient();
const { chat_id, content } = postMessageBodySchema.parse(req.body);
const chat = await supabase
.from("chats")
.select()
.eq("id", chat_id)
.single()
.then(({ data, error }) => {
if (error) {
logger.error({
message: "Chat retrieval error",
error,
});
throw new Error("Chat retrieval error");
}
if (!data) {
logger.error({
message: "Chat not found",
});
throw new Error("Chat not found");
}
return data as ChatsRow;
});
const insertMessage = await addUserMessage(
supabase,
{ chat_id, content },
chat,
logger,
);
if (insertMessage.error) {
logger.error({
message: "Message creation error",
error: insertMessage.error,
});
return next(new Error("Message creation error"));
}
res.status(insertMessage.status).send(JSON.stringify(insertMessage.data));
});
return router;
}