From 6a9204b0aaadea8f929c62dbc49abe63760aa638 Mon Sep 17 00:00:00 2001
From: "Embruch, Gerd" <gerd.embruch@uni-hamburg.de>
Date: Mon, 29 Jul 2024 11:13:59 +0200
Subject: [PATCH] fixed extendChat by adding findRecordByID(); added exceptions
 for registering users by artillery

---
 __tests__/manualREST/ollama.rest |  2 +-
 controllers/AI.js                | 19 +++----------------
 controllers/User.js              | 13 +++++++++++++
 utils/handleAI.js                |  4 ----
 utils/handleDB.js                | 26 +++++++++++++++++++++++++-
 5 files changed, 42 insertions(+), 22 deletions(-)

diff --git a/__tests__/manualREST/ollama.rest b/__tests__/manualREST/ollama.rest
index 3f059a9..a3d732a 100644
--- a/__tests__/manualREST/ollama.rest
+++ b/__tests__/manualREST/ollama.rest
@@ -102,7 +102,7 @@ Accept: application/json
 Content-Type: application/json
 
 {
-  "input": "Under what path could members of the working group can find the exam git directory?",
+  "input": "When does mocking stops feeling like torture?",
   "model": "llama3"
 }
 
diff --git a/controllers/AI.js b/controllers/AI.js
index 82c6ccb..5e7e27b 100644
--- a/controllers/AI.js
+++ b/controllers/AI.js
@@ -2,7 +2,7 @@ import { Ollama } from 'ollama';
 import Chat from "../models/Chat.js";
 import { aiDeleteModel, aiGetModels, aiGetModel, aiInstallModel, aiIsRunning, summarizeText } from "../utils/handleAI.js";
 import { mapStoredMessagesToChatMessages } from "@langchain/core/messages";
-import { createRecord, findOneRecord, findRecords } from '../utils/handleDB.js';
+import { createRecord, findOneRecord, findRecordByID, findRecords } from '../utils/handleDB.js';
 import { prefillDocumentObject } from '../utils/handleSchemes.js';
 
 
@@ -95,21 +95,15 @@ export const getChat = async (req, res, next) => {
   // IF CHATID GIVEN
   try {
     // fetch chat record
-    const record = await findOneRecord(Chat, { id: req.body.chatId });
+    const record = await findRecordByID(Chat, req.body.chatId);
 
     if (!record) {
       return res.status(404).json({ message: `No chat history with ID ${req.body.chatId} found.` });
     }
-    console.log("🚀 ~ getChat ~ record SIC:", record);
-
-
     // remember chat history
     // cite: https://js.langchain.com/v0.1/docs/modules/memory/chat_messages/custom/
     req.body.chatHistory = mapStoredMessagesToChatMessages(record.chatHistory);
-
-    console.log("🚀 ~ getChat ~ req.body.chatHistory:", req.body.chatHistory);
-
-
+    // go on
     next();
   } catch (error) {
     next(error);
@@ -140,15 +134,8 @@ export const createChat = async (model, input) => {
   try {
     // create chat title
     const title = await summarizeText(model, input);
-
-    console.log("🚀 ~ createChat ~ title:", title);
-
     // create record
     const record = await createRecord(Chat, prefillDocumentObject(Chat, { title }));
-
-    console.log("🚀 ~ createChat ~ record:", record);
-
-
     // return record id
     return record.id;
   } catch (error) {
diff --git a/controllers/User.js b/controllers/User.js
index 2dbeee1..96c8bf2 100644
--- a/controllers/User.js
+++ b/controllers/User.js
@@ -7,10 +7,23 @@ import { prefillDocumentObject, hideConfidentialFields } from '../utils/handleSc
  */
 export const createUser = async (req, res, next) => {
   try {
+    // autoverify if user-agent is Artillery
+    const isArtilleryAgent = req.get('user-agent').includes('Artillery');
+    if (isArtilleryAgent) {
+      req.body.verified = true;
+    }
+    // console.log("🚀 ~ createUser ~ isArtilleryAgent:", isArtilleryAgent);
+    // return res.status(200).json({ message: 'tmp abort', isArtilleryAgent });
+
     // create user object
     const newRecord = await createRecord(User, prefillDocumentObject(User, req.body));
     // remember document but remove confidential info
     req.document = hideConfidentialFields(User, newRecord);
+    // return if user-agent is Artillery
+    if (isArtilleryAgent) {
+      return res.status(201).json({ message: 'User created', document: req.document });
+    }
+    // continue to send verification
     next();
     // on error
   } catch (error) {
diff --git a/utils/handleAI.js b/utils/handleAI.js
index b467eb8..1771ae7 100644
--- a/utils/handleAI.js
+++ b/utils/handleAI.js
@@ -193,9 +193,5 @@ export const chat = async (req, res, next) => {
   ]);
 
   // return the answer
-  console.log('Answer: ', result.answer);
-  console.log('Chat: ', chat);
-
-
   return res.json({ answer: result.answer, chat });
 };
\ No newline at end of file
diff --git a/utils/handleDB.js b/utils/handleDB.js
index 32cf015..c1789ec 100644
--- a/utils/handleDB.js
+++ b/utils/handleDB.js
@@ -77,6 +77,29 @@ export const findOneRecord = async (model, searchObject = {}, fieldHandler = '')
   }
 };
 
+/**
+ * find record by ID
+ *
+ * @param   {mongoose model}  model         [required] model to search the record in
+ * @param   {string}          ID            [required] ID to search the record with
+ * @param   {string}          fieldHandler  [optional] additional fields to return or drop, i.e. '+password'
+ *
+ * @return  {object}              found document
+ */
+export const findRecordByID = async (model, id, fieldHandler = '') => {
+  try {
+    let foundRecord;
+    if (!fieldHandler) {
+      foundRecord = await model.findById(id);
+    } else {
+      foundRecord = await model.findById(id).select(fieldHandler);
+    }
+    return foundRecord;
+  } catch (error) {
+    throw error;
+  }
+};
+
 /**
  * find multiple records
  *
@@ -168,7 +191,8 @@ export const extendChat = async (chatId, messages) => {
   }
   try {
     // fetch chat record
-    const record = await findOneRecord(Chat, { id: chatId });
+    const record = await findRecordByID(Chat, chatId);
+
     // push new message into chat history
     const serializedMessages = mapChatMessagesToStoredMessages(messages);
     record.chatHistory ? record.chatHistory.push(...serializedMessages) : record.chatHistory = serializedMessages;
-- 
GitLab