Skip to content

Commit

Permalink
chore: remove Messages model dependency of Rooms model (RocketChat#31272
Browse files Browse the repository at this point in the history
)
  • Loading branch information
sampaiodiego authored Dec 29, 2023
1 parent 46a625b commit 7610aa4
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ export class ImportDataConverter {

for await (const rid of rids) {
try {
await Rooms.resetLastMessageById(rid);
await Rooms.resetLastMessageById(rid, null);
} catch (e) {
this._logger.warn(`Failed to update last message of room ${rid}`);
this._logger.error(e);
Expand Down
4 changes: 3 additions & 1 deletion apps/meteor/app/lib/server/functions/cleanRoomHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ export async function cleanRoomHistory({

if (count) {
const lastMessage = await Messages.getLastVisibleMessageSentWithNoTypeByRoomId(rid);
await Rooms.resetLastMessageById(rid, lastMessage);

await Rooms.resetLastMessageById(rid, lastMessage, -count);

void api.broadcast('notify.deleteMessageBulk', rid, {
rid,
excludePinned,
Expand Down
14 changes: 6 additions & 8 deletions apps/meteor/app/lib/server/functions/deleteMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,14 @@ export async function deleteMessage(message: IMessage, user: IUser): Promise<voi
const room = await Rooms.findOneById(message.rid, { projection: { lastMessage: 1, prid: 1, mid: 1, federated: 1 } });

// update last message
if (settings.get('Store_Last_Message')) {
if (!room?.lastMessage || room.lastMessage._id === message._id) {
const lastMessageNotDeleted = await Messages.getLastVisibleMessageSentWithNoTypeByRoomId(message.rid);
await Rooms.resetLastMessageById(message.rid, lastMessageNotDeleted);
}
if (settings.get('Store_Last_Message') && (!room?.lastMessage || room.lastMessage._id === message._id)) {
const lastMessageNotDeleted = await Messages.getLastVisibleMessageSentWithNoTypeByRoomId(message.rid);
await Rooms.resetLastMessageById(message.rid, lastMessageNotDeleted, -1);
} else {
// decrease message count
await Rooms.decreaseMessageCountById(message.rid, 1);
}

// decrease message count
await Rooms.decreaseMessageCountById(message.rid, 1);

await callbacks.run('afterDeleteMessage', deletedMsg, room);

if (keepHistory || showDeletedStatus) {
Expand Down
12 changes: 0 additions & 12 deletions apps/meteor/server/models/raw/Messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import type {
IMessageWithPendingFileImport,
} from '@rocket.chat/core-typings';
import type { FindPaginated, IMessagesModel } from '@rocket.chat/model-typings';
import { Rooms } from '@rocket.chat/models';
import type { PaginatedRequest } from '@rocket.chat/rest-typings';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import type {
Expand Down Expand Up @@ -1340,8 +1339,6 @@ export class MessagesRaw extends BaseRaw<IMessage> implements IMessagesModel {

const data = Object.assign(record, extraData);

await Rooms.incMsgCountById(rid, 1);

return this.insertOne(data);
}

Expand Down Expand Up @@ -1464,10 +1461,6 @@ export class MessagesRaw extends BaseRaw<IMessage> implements IMessagesModel {

if (!limit) {
const count = (await this.deleteMany(query)).deletedCount - notCountedMessages;
if (count) {
// decrease message count
await Rooms.decreaseMessageCountById(rid, count);
}

return count;
}
Expand All @@ -1481,11 +1474,6 @@ export class MessagesRaw extends BaseRaw<IMessage> implements IMessagesModel {
})
).deletedCount - notCountedMessages;

if (count) {
// decrease message count
await Rooms.decreaseMessageCountById(rid, count);
}

return count;
}

Expand Down
17 changes: 5 additions & 12 deletions apps/meteor/server/models/raw/Rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1566,20 +1566,13 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.updateOne(query, update);
}

async resetLastMessageById(_id: IRoom['_id'], lastMessage: IRoom['lastMessage']): Promise<UpdateResult> {
async resetLastMessageById(_id: IRoom['_id'], lastMessage: IRoom['lastMessage'] | null, msgCountDelta?: number): Promise<UpdateResult> {
const query: Filter<IRoom> = { _id };

const update: UpdateFilter<IRoom> = lastMessage
? {
$set: {
lastMessage,
},
}
: {
$unset: {
lastMessage: 1,
},
};
const update = {
...(lastMessage ? { $set: { lastMessage } } : { $unset: { lastMessage: 1 as const } }),
...(msgCountDelta ? { $inc: { msgs: msgCountDelta } } : {}),
};

return this.updateOne(query, update);
}
Expand Down
22 changes: 14 additions & 8 deletions apps/meteor/server/services/messages/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,24 @@ export class MessageService extends ServiceClassInternal implements IMessageServ
if (!username) {
throw new Error('The username cannot be empty.');
}
const result = await Messages.createWithTypeRoomIdMessageUserAndUnread(
type,
rid,
message,
{ _id: userId, username, name },
settings.get('Message_Read_Receipt_Enabled'),
extraData,
);

const [result] = await Promise.all([
Messages.createWithTypeRoomIdMessageUserAndUnread(
type,
rid,
message,
{ _id: userId, username, name },
settings.get('Message_Read_Receipt_Enabled'),
extraData,
),
Rooms.incMsgCountById(rid, 1),
]);

void broadcastMessageSentEvent({
id: result.insertedId,
broadcastCallback: async (message) => this.api?.broadcast('message.sent', message),
});

return result.insertedId;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/model-typings/src/models/IRoomsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export interface IRoomsModel extends IBaseModel<IRoom> {
incUsersCountById(rid: string, inc: number): Promise<UpdateResult>;
incUsersCountNotDMsByIds(rids: string[], inc: number): Promise<Document | UpdateResult>;
setLastMessageById(rid: string, lastMessage: IRoom['lastMessage']): Promise<UpdateResult>;
resetLastMessageById(rid: string, lastMessage?: IMessage | null): Promise<UpdateResult>;
resetLastMessageById(rid: string, lastMessage: IMessage | null, msgCountDelta?: number): Promise<UpdateResult>;
replaceUsername(username: string, newUsername: string): Promise<UpdateResult | Document>;
replaceMutedUsername(username: string, newUsername: string): Promise<UpdateResult | Document>;
replaceUsernameOfUserByUserId(userId: string, newUsername: string): Promise<UpdateResult | Document>;
Expand Down

0 comments on commit 7610aa4

Please sign in to comment.