Skip to content

Commit

Permalink
Chore: Improve performance of messages’ watcher (#20519)
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigok authored Feb 4, 2021
1 parent 6878003 commit b2ecfa8
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions server/modules/watchers/watchers.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import mem from 'mem';

import { SubscriptionsRaw } from '../../../app/models/server/raw/Subscriptions';
import { UsersRaw } from '../../../app/models/server/raw/Users';
import { SettingsRaw } from '../../../app/models/server/raw/Settings';
Expand All @@ -13,7 +15,7 @@ import { IBaseRaw } from '../../../app/models/server/raw/BaseRaw';
import { LivechatInquiryRaw } from '../../../app/models/server/raw/LivechatInquiry';
import { IBaseData } from '../../../definition/IBaseData';
import { IPermission } from '../../../definition/IPermission';
import { ISetting } from '../../../definition/ISetting';
import { ISetting, SettingValue } from '../../../definition/ISetting';
import { IInquiry } from '../../../definition/IInquiry';
import { UsersSessionsRaw } from '../../../app/models/server/raw/UsersSessions';
import { IUserSession } from '../../../definition/IUserSession';
Expand Down Expand Up @@ -83,6 +85,13 @@ export function initWatchers(models: IModelsParam, broadcast: BroadcastCallback,
EmailInbox,
} = models;

const getSettingCached = mem(async (setting: string): Promise<SettingValue> => Settings.getValueById(setting), { maxAge: 10000 });

const getUserNameCached = mem(async (userId: string): Promise<string | undefined> => {
const user = await Users.findOneById(userId, { projection: { name: 1 } });
return user?.name;
}, { maxAge: 10000 });

watch<IMessage>(Messages, async ({ clientAction, id, data }) => {
switch (clientAction) {
case 'inserted':
Expand All @@ -93,18 +102,16 @@ export function initWatchers(models: IModelsParam, broadcast: BroadcastCallback,
}

if (message._hidden !== true && message.imported == null) {
const UseRealName = await Settings.getValueById('UI_Use_Real_Name') === true;
const UseRealName = await getSettingCached('UI_Use_Real_Name') === true;

if (UseRealName) {
if (message.u?._id) {
const user = await Users.findOneById(message.u._id);
message.u.name = user?.name;
message.u.name = await getUserNameCached(message.u._id);
}

if (message.mentions?.length) {
for await (const mention of message.mentions) {
const user = await Users.findOneById(mention._id);
mention.name = user?.name;
mention.name = await getUserNameCached(mention._id);
}
}
}
Expand Down

0 comments on commit b2ecfa8

Please sign in to comment.