| 145 | } |
| 146 | |
| 147 | class MessageClass extends mongoose.Model { |
| 148 | public static async getList({ userId, chatId, batchNumberForMessages, limit }) { |
| 149 | await this.checkPermission({ userId, chatId }); |
| 150 | |
| 151 | const filter = { chatId, parentMessageId: null }; |
| 152 | |
| 153 | const messages = await this.find(filter) |
| 154 | .sort({ createdAt: -1, _id: 1 }) |
| 155 | .skip((batchNumberForMessages - 1) * limit) |
| 156 | .limit(limit) |
| 157 | .setOptions({ lean: true }); |
| 158 | |
| 159 | // use for...of instead of forEach |
| 160 | // forEach does not care about promises from await |
| 161 | for (const message of messages) { |
| 162 | const threadMessages = await this.find({ |
| 163 | parentMessageId: message._id.toString(), |
| 164 | }); |
| 165 | |
| 166 | message.countOfThreadMessages = threadMessages.length; |
| 167 | } |
| 168 | |
| 169 | return messages; |
| 170 | } |
| 171 | |
| 172 | public static async getListForThread({ userId, chatId, messageId }) { |
| 173 | await this.checkPermission({ userId, chatId }); |
| 174 | |
| 175 | const filter = { chatId, parentMessageId: messageId }; |
| 176 | |
| 177 | return this.find(filter).sort({ createdAt: 1, _id: 1 }).setOptions({ lean: true }); |
| 178 | } |
| 179 | |
| 180 | // done: add parentMessageId |
| 181 | public static async addOrEdit({ content, chatId, teamId, userId, id, files, parentMessageId }) { |
| 182 | if (!content || !teamId) { |
| 183 | throw new Error('Bad data'); |
| 184 | } |
| 185 | |
| 186 | const { isSubscriptionActiveForAccount, isTrialPeriodOverForAccount } = |
| 187 | await User.getSubscriptionStatus(userId); |
| 188 | |
| 189 | if (isTrialPeriodOverForAccount && !isSubscriptionActiveForAccount) { |
| 190 | throw new Error('This team is not subscribed to a paid plan and free trial period is over.'); |
| 191 | } |
| 192 | |
| 193 | await Chat.updateOne({ _id: chatId }, { lastUpdatedAt: new Date() }); |
| 194 | |
| 195 | if (id) { |
| 196 | const editedMessage = await this.edit({ |
| 197 | content, |
| 198 | chatId, |
| 199 | userId, |
| 200 | id, |
| 201 | }); |
| 202 | |
| 203 | // no realtime update for editing message |
| 204 | return { message: editedMessage, userIdsToNotify: [] }; |
nothing calls this directly
no outgoing calls
no test coverage detected