Building a Chat Manager with JavaScript

Building the Chat Manager

Welcome back! In the previous lesson, we explored the importance of a robust system prompt and how it guides the behavior of our chatbot. Now, we will delve into the next step of our journey: building the Chat Manager. This lesson will focus on the model layer of the MVC (Model-View-Controller) architecture, which is crucial for organizing and managing data in a structured way. The ChatManager class will be the core component of our model layer, responsible for managing chat data effectively. By the end of this lesson, you will understand how to create, manage, and retrieve chat data using the ChatManager class.

Initializing the ChatManager

The ChatManager class is designed to handle the storage and management of chat data. It serves as the backbone of our chatbot's data management system. We'll start by setting up the class and then gradually add methods to handle chat creation, message addition, and conversation retrieval.

Let's begin by defining the ChatManager class and its constructor. The constructor initializes an empty object, this.chats, which will store all chat data.

class ChatManager {
    constructor() {
        this.chats = {};  // user_id -> chat_id -> chat_data
    }
}

In this setup, this.chats is a nested object where the first key is the user_id, and the second key is the chat_id. This structure allows us to efficiently manage multiple chats for different users.

Creating a New Chat

Next, we'll add the createChat method. This method is responsible for creating a new chat entry for a user. It takes three parameters: userId, chatId, and systemPrompt.

class ChatManager {
    constructor() {
        this.chats = {};
    }

    createChat(userId, chatId, systemPrompt) {
        if (!this.chats[userId]) {
            this.chats[userId] = {};
        }
        
        this.chats[userId][chatId] = {
            systemPrompt: systemPrompt,
            messages: []
        };
    }
}

The createChat method checks if the userId exists in this.chats. If not, it creates a new entry. Then, it initializes the chat with the provided systemPrompt and an empty array for messages.

Retrieving a Chat

To access a specific chat, we need the getChat method. This method retrieves a chat based on the userId and chatId.

getChat(userId, chatId) {
    return this.chats[userId]?.[chatId];
}

The getChat method uses optional chaining to safely access the nested object, returning the chat data if it exists.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal