| 126 | } |
| 127 | |
| 128 | try { |
| 129 | const messages = chat.messages || []; |
| 130 | chat.messages = messages.filter((message: any) => !message.isDeleted); |
| 131 | } catch (error) { |
| 132 | console.error('Error parsing messages JSON:', error); |
| 133 | chat.messages = []; |
| 134 | } |
| 135 | |
| 136 | return chat; |
| 137 | } |
| 138 | |
| 139 | async getProjectByChatId(chatId: string): Promise<Project> { |
| 140 | const chat = await this.chatRepository.findOne({ |
| 141 | where: { id: chatId, isDeleted: false }, |
| 142 | relations: ['project'], |
| 143 | }); |
| 144 | |
| 145 | return chat ? chat.project : null; |
| 146 | } |
| 147 | |
| 148 | async createChat(userId: string, newChatInput: NewChatInput): Promise<Chat> { |
| 149 | const user = await this.userRepository.findOne({ where: { id: userId } }); |
| 150 | if (!user) { |
| 151 | throw new Error('User not found'); |
| 152 | } |
| 153 | |
| 154 | const newChat = this.chatRepository.create({ |
| 155 | title: newChatInput.title, |
| 156 | messages: [], |
| 157 | createdAt: new Date(), |
| 158 | updatedAt: new Date(), |
| 159 | user: user, |
| 160 | }); |
| 161 | |
| 162 | return await this.chatRepository.save(newChat); |
| 163 | } |
| 164 | |
| 165 | async createChatWithMessage( |
| 166 | userId: string, |