From d806c7e5813fd801ba4259f84ebb0d2657bb6e54 Mon Sep 17 00:00:00 2001 From: ItzCrazyKns Date: Sat, 29 Jun 2024 11:09:13 +0530 Subject: [PATCH] feat(app): add chats route --- src/routes/chats.ts | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/routes/index.ts | 2 ++ 2 files changed, 47 insertions(+) create mode 100644 src/routes/chats.ts diff --git a/src/routes/chats.ts b/src/routes/chats.ts new file mode 100644 index 0000000..f970ba4 --- /dev/null +++ b/src/routes/chats.ts @@ -0,0 +1,45 @@ +import express from 'express'; +import logger from '../utils/logger'; +import db from '../db/index'; +import { eq } from 'drizzle-orm'; +import { chats, messages } from '../db/schema'; + +const router = express.Router(); + +router.get('/', async (_, res) => { + try { + let chats = await db.query.chats.findMany(); + + /* Reorder the chats (in opposite direction) */ + + chats = chats.reverse(); + + return res.status(200).json({ chats: chats }); + } catch (err) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error in getting chats: ${err.message}`); + } +}); + +router.get('/:id', async (req, res) => { + try { + const chatExists = await db.query.chats.findFirst({ + where: eq(chats.id, req.params.id), + }); + + if (!chatExists) { + return res.status(404).json({ message: 'Chat not found' }); + } + + const chatMessages = await db.query.messages.findMany({ + where: eq(messages.chatId, req.params.id), + }); + + return res.status(200).json({ chat: chatExists, messages: chatMessages }); + } catch (err) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error in getting chat: ${err.message}`); + } +}); + +export default router; diff --git a/src/routes/index.ts b/src/routes/index.ts index 257e677..af928ab 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -4,6 +4,7 @@ import videosRouter from './videos'; import configRouter from './config'; import modelsRouter from './models'; import suggestionsRouter from './suggestions'; +import chatsRouter from './chats'; const router = express.Router(); @@ -12,5 +13,6 @@ router.use('/videos', videosRouter); router.use('/config', configRouter); router.use('/models', modelsRouter); router.use('/suggestions', suggestionsRouter); +router.use('/chats', chatsRouter); export default router;