-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathchatLogger.ts
40 lines (32 loc) · 1.14 KB
/
chatLogger.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
import fs from 'fs-extra';
import path from 'path';
interface ChatHistory {
timestamp: string;
question: string;
answer: string;
}
const ensureLogDirectory = (logDirectory: string): void => {
fs.ensureDirSync(logDirectory);
};
const getLogFilename = (): string => {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
return `${year}-${month}-${day}.json`;
};
const logChat = async (logDirectory: string, question: string, answer: string): Promise<void> => {
const timestamp = new Date().toISOString();
const chatHistory: ChatHistory = { timestamp, question, answer };
const logFilename = getLogFilename();
const logFilePath = path.join(logDirectory, logFilename);
ensureLogDirectory(logDirectory);
if (!fs.existsSync(logFilePath)) {
await fs.writeJson(logFilePath, [chatHistory]);
} else {
const chatHistoryArray = await fs.readJson(logFilePath);
chatHistoryArray.push(chatHistory);
await fs.writeJson(logFilePath, chatHistoryArray);
}
};
export default logChat;