Session Management Commands

Created on: September 28, 2024

Answered using OpenAI 01 Preview by OpenAI01

Question

import { bot } from './instance.js';
import { getSession, setSession, getUserSession, setUserSession, createSession } from '../utils/session.js';

const start = async (chatId, userId, text) => {
const sessionId = text.split(' ')[1];
if (!sessionId) return bot.sendMessage(chatId, 'Please provide a session ID.');

let session = await getSession(sessionId) || await createSession(sessionId);
session.userId = userId;
session.chatId = chatId;
await setSession(sessionId, session);
await setUserSession(userId, sessionId);

bot.sendMessage(chatId, `Welcome to session ${sessionId}!`);
};

const clear = async (chatId, userId) => {
const sessionId = await getUserSession(userId);
if (!sessionId) return bot.sendMessage(chatId, 'No active session.');

const session = await getSession(sessionId);
if (!session) return bot.sendMessage(chatId, 'Session not found.');
session.commands.push({ type: 'CLEAR' });
session.promptNumber = 2;
await setSession(sessionId, session);

bot.sendMessage(chatId, 'Session cleared.');
};

const request = async (chatId, userId, text) => {
const sessionId = await getUserSession(userId);
if (!sessionId) return bot.sendMessage(chatId, 'No active session. Use /start <session_id> to start.');

const session = await getSession(sessionId);
if (!session) return bot.sendMessage(chatId, 'Session not found.');
session.commands.push({ type: 'RUN', text, promptNumber: session.promptNumber });
session.promptNumber += 2;
await setSession(sessionId, session);

bot.sendMessage(chatId, 'Processing your request...');
};

export const handleMessage = async (msg) => {
const chatId = msg.chat.id, userId = msg.from.id, text = msg.text?.trim() || '';
try {
if (text.startsWith('/start')) await start(chatId, userId, text);
else if (text === '/clear') await clear(chatId, userId);
else await request(chatId, userId, text);
} catch (error) {
console.error('Error handling message:', error);
bot.sendMessage(chatId, 'An error occurred.');
}
};

// make it so that there is less code duplication in functions by adding new functions

Thought

Identifying duplication

I’m noting that the functions in the JavaScript code share a common pattern—retrieving the sessionId and session, and handling errors, which likely leads to code duplication.

Refactoring the code

I’m focusing on reducing duplication by adding new functions. Starting with getSessionForUser, I map out how the start function handles session ID retrieval, session creation, and message sending.

Clarifying session handling

I’m piecing together the clear function to manage active sessions. It gets the sessionId, ensures the session exists, updates commands, and sends a completion message.

Enhancing efficiency

I’m thinking about improving the code by creating functions to simplify getting sessions for users and handling errors. This should streamline the process significantly.

Refining session handling

I’m thinking about creating a function to manage user sessions, including error messages for missing or invalid sessions. This function can streamline the process and enhance user guidance.

Piecing together sessions

I’m thinking about a helper function to parse session IDs. Also, crafting getSessionByUserId to fetch active sessions with error handling for different outcomes. Progressing towards robust session management.

Breaking down the code
I noticed that session retrieval and creation are repeated, so I'll create a function to handle these tasks, aiming to simplify and minimize redundancy.

Answer

import { bot } from './instance.js'; import { getSession, setSession, getUserSession, setUserSession, createSession, } from '../utils/session.js'; // Helper function to extract session ID from text const parseSessionId = (text) => { const parts = text.trim().split(' '); return parts.length > 1 ? parts[1] : null; }; // Helper function to get or create a session const getOrCreateSession = async (sessionId) => { return (await getSession(sessionId)) || (await createSession(sessionId)); }; // Helper function to retrieve the active session for a user const retrieveUserSession = async (chatId, userId, noSessionMsg) => { const sessionId = await getUserSession(userId); if (!sessionId) { await bot.sendMessage(chatId, noSessionMsg); return null; } const session = await getSession(sessionId); if (!session) { await bot.sendMessage(chatId, 'Session not found.'); return null; } return { sessionId, session }; }; const start = async (chatId, userId, text) => { const sessionId = parseSessionId(text); if (!sessionId) return bot.sendMessage(chatId, 'Please provide a session ID.'); const session = await getOrCreateSession(sessionId); session.userId = userId; session.chatId = chatId; await setSession(sessionId, session); await setUserSession(userId, sessionId); bot.sendMessage(chatId, `Welcome to session ${sessionId}!`); }; const clear = async (chatId, userId) => { const result = await retrieveUserSession(chatId, userId, 'No active session.'); if (!result) return; const { sessionId, session } = result; session.commands.push({ type: 'CLEAR' }); session.promptNumber = 2; await setSession(sessionId, session); bot.sendMessage(chatId, 'Session cleared.'); }; const request = async (chatId, userId, text) => { const result = await retrieveUserSession( chatId, userId, 'No active session. Use /start <session_id> to start.' ); if (!result) return; const { sessionId, session } = result; session.commands.push({ type: 'RUN', text, promptNumber: session.promptNumber }); session.promptNumber += 2; await setSession(sessionId, session); bot.sendMessage(chatId, 'Processing your request...'); }; export const handleMessage = async (msg) => { const chatId = msg.chat.id, userId = msg.from.id, text = msg.text?.trim() || ''; try { if (text.startsWith('/start')) await start(chatId, userId, text); else if (text === '/clear') await clear(chatId, userId); else await request(chatId, userId, text); } catch (error) { console.error('Error handling message:', error); bot.sendMessage(chatId, 'An error occurred.'); } };

Explanation:

To reduce code duplication, we've introduced three helper functions:

  1. parseSessionId(text): Extracts the session ID from the input text.
  2. getOrCreateSession(sessionId): Retrieves an existing session or creates a new one if it doesn't exist.
  3. retrieveUserSession(chatId, userId, noSessionMsg): Retrieves the active session for a user, sending an error message if no session is found.

By using these helper functions in the start, clear, and request functions, we've eliminated repetitive code related to session handling and error messaging. This makes the code cleaner, more maintainable, and reduces the likelihood of bugs due to duplicated logic.

Share this Q&A