Setup Back End
When it comes to the Back End, there's multiple solutions for how you can store your chatbot data. What we want, is a solution where we can save conversations and see old conversations the user has had with the OpenAI chatbot. The old conversations should also be possible to continue after the session is closed and you should be able to close sonversations you're done with.
One example is to use FileStorage, which can be good for smaller applications and has an easy setup. But feel free to use whichever Back End storage solution you see fit and/or you would like to learn more about.
Below you can see an example of how to handle data saving with filestorage:
// fileStorage.js
const fs = require('fs')
const path = require('path')
const filePath = path.join(__dirname, 'chatData.json')
function saveConversation(userMessage, botResponse) {
const conversation = {
userMessage,
botResponse,
timestamp: new Date().toISOString(),
}
const data = JSON.parse(fs.readFileSync(filePath, 'utf-8') || '[]')
data.push(conversation)
fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
}
function getAllConversations() {
const data = JSON.parse(fs.readFileSync(filePath, 'utf-8') || '[]')
return data
}
module.exports = { saveConversation, getAllConversations }