File size: 7,234 Bytes
27127dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { 
  type Message, 
  type InsertMessage, 
  type Conversation, 
  type InsertConversation,
  type User,
  PersonalityType,
  messageRoleSchema,
  messages,
  conversations,
  users
} from "@shared/schema";
import { db } from "./db";
import { eq, desc, asc } from "drizzle-orm";
import { nanoid } from "nanoid";
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { pool } from './db';

export interface IStorage {
  // Message operations
  getMessages(conversationId: string): Promise<Message[]>;
  createMessage(message: InsertMessage): Promise<Message>;
  deleteMessages(conversationId: string): Promise<void>;
  
  // Conversation operations
  getConversation(id: string): Promise<Conversation | undefined>;
  getConversations(): Promise<Conversation[]>;
  getUserConversations(userId: number): Promise<Conversation[]>;
  createConversation(conversation: InsertConversation): Promise<Conversation>;
  deleteConversation(id: string): Promise<boolean>;
  updateConversationPersonality(id: string, personality: PersonalityType): Promise<Conversation | undefined>;
  updateConversationTitle(id: string, title: string): Promise<Conversation | undefined>;
  
  // User profile operations
  getUserProfile(id: number): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  createUser(userData: any): Promise<User>;
  updateUserProfile(id: number, profile: Partial<User>): Promise<User | undefined>;
  
  // Session operations
  sessionStore: session.Store;
}

export class DatabaseStorage implements IStorage {
  sessionStore: session.Store;

  constructor() {
    // Initialize PostgreSQL session store
    const PgStore = connectPgSimple(session);
    this.sessionStore = new PgStore({
      pool,
      createTableIfMissing: true,
    });

    // Initialize default conversation if it doesn't exist
    this.initializeDefaultConversation();
  }

  private async initializeDefaultConversation() {
    try {
      const defaultConversation = await this.getConversation("default");
      if (!defaultConversation) {
        await this.createConversation({
          id: "default",
          title: "New Conversation",
          personality: "general"
        });
      }
    } catch (error) {
      console.error("Error initializing default conversation:", error);
    }
  }

  // Message operations
  async getMessages(conversationId: string): Promise<Message[]> {
    return db
      .select()
      .from(messages)
      .where(eq(messages.conversationId, conversationId))
      .orderBy(asc(messages.createdAt));
  }

  async createMessage(insertMessage: InsertMessage): Promise<Message> {
    const [newMessage] = await db
      .insert(messages)
      .values({
        ...insertMessage,
        createdAt: new Date()
      })
      .returning();
    
    return newMessage;
  }
  
  async deleteMessages(conversationId: string): Promise<void> {
    await db
      .delete(messages)
      .where(eq(messages.conversationId, conversationId));
  }

  // Conversation operations
  async getConversation(id: string): Promise<Conversation | undefined> {
    const [conversation] = await db
      .select()
      .from(conversations)
      .where(eq(conversations.id, id));
    
    return conversation;
  }

  async getConversations(): Promise<Conversation[]> {
    return db
      .select()
      .from(conversations)
      .orderBy(desc(conversations.createdAt));
  }

  async createConversation(conversation: InsertConversation): Promise<Conversation> {
    // If the conversation already exists, update it
    if (conversation.id) {
      const existingConversation = await this.getConversation(conversation.id);
      if (existingConversation) {
        const [updatedConversation] = await db
          .update(conversations)
          .set({
            title: conversation.title,
            personality: conversation.personality || "general",
            // Only update userId if provided
            ...(conversation.userId && { userId: conversation.userId })
          })
          .where(eq(conversations.id, conversation.id))
          .returning();
        
        return updatedConversation;
      }
    }
    
    // Otherwise, create a new conversation
    const [newConversation] = await db
      .insert(conversations)
      .values({
        id: conversation.id || nanoid(),
        title: conversation.title,
        personality: conversation.personality || "general",
        userId: conversation.userId, // Include the user ID (can be null for unassociated conversations)
        createdAt: new Date()
      })
      .returning();
    
    return newConversation;
  }
  
  async deleteConversation(id: string): Promise<boolean> {
    // Don't allow deleting the default conversation
    if (id === "default") {
      return false;
    }
    
    try {
      // Delete associated messages first
      await this.deleteMessages(id);
      
      // Then delete the conversation
      const [deletedConversation] = await db
        .delete(conversations)
        .where(eq(conversations.id, id))
        .returning();
      
      return !!deletedConversation;
    } catch (error) {
      console.error("Error deleting conversation:", error);
      return false;
    }
  }
  
  async updateConversationPersonality(id: string, personality: PersonalityType): Promise<Conversation | undefined> {
    const [updatedConversation] = await db
      .update(conversations)
      .set({ personality })
      .where(eq(conversations.id, id))
      .returning();
    
    return updatedConversation;
  }
  
  async updateConversationTitle(id: string, title: string): Promise<Conversation | undefined> {
    const [updatedConversation] = await db
      .update(conversations)
      .set({ title })
      .where(eq(conversations.id, id))
      .returning();
    
    return updatedConversation;
  }
  
  // User operations
  async getUserProfile(id: number): Promise<User | undefined> {
    const [user] = await db
      .select()
      .from(users)
      .where(eq(users.id, id));
    
    return user;
  }
  
  async getUserByUsername(username: string): Promise<User | undefined> {
    const [user] = await db
      .select()
      .from(users)
      .where(eq(users.username, username));
    
    return user;
  }
  
  async createUser(userData: any): Promise<User> {
    const [user] = await db
      .insert(users)
      .values(userData)
      .returning();
    
    return user;
  }
  
  async updateUserProfile(id: number, profile: Partial<User>): Promise<User | undefined> {
    // Remove sensitive information that shouldn't be updated this way
    const { password, ...updateData } = profile;
    
    const [updatedUser] = await db
      .update(users)
      .set(updateData as any)
      .where(eq(users.id, id))
      .returning();
    
    return updatedUser;
  }
  
  // Filter conversations by user ID
  async getUserConversations(userId: number): Promise<Conversation[]> {
    return db
      .select()
      .from(conversations)
      .where(eq(conversations.userId, userId))
      .orderBy(desc(conversations.createdAt));
  }
}

// Use the database storage for production
export const storage = new DatabaseStorage();