Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IMPROVE] Send only relevant data via WebSocket #22258

Merged
merged 3 commits into from Jun 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 25 additions & 2 deletions server/modules/watchers/watchers.module.ts
Expand Up @@ -66,6 +66,21 @@ type Watcher = <T extends IBaseData>(model: IBaseRaw<T>, fn: (event: IChange<T>)

type BroadcastCallback = <T extends keyof EventSignatures>(event: T, ...args: Parameters<EventSignatures[T]>) => Promise<void>;

const hasKeys = (requiredKeys: string[]): (data?: Record<string, any>) => boolean =>
(data?: Record<string, any>): boolean => {
if (!data) {
return false;
}

return Object.keys(data)
.filter((key) => key !== '_id')
.map((key) => key.split('.')[0])
.some((key) => requiredKeys.includes(key));
};

const hasRoomFields = hasKeys(Object.keys(roomFields));
const hasSubscriptionFields = hasKeys(Object.keys(subscriptionFields));

const startMonitor = typeof process.env.DISABLE_PRESENCE_MONITOR === 'undefined'
|| !['true', 'yes'].includes(String(process.env.DISABLE_PRESENCE_MONITOR).toLowerCase());

Expand Down Expand Up @@ -125,10 +140,14 @@ export function initWatchers(models: IModelsParam, broadcast: BroadcastCallback,
}
});

watch<ISubscription>(Subscriptions, async ({ clientAction, id }) => {
watch<ISubscription>(Subscriptions, async ({ clientAction, id, data, diff }) => {
switch (clientAction) {
case 'inserted':
case 'updated': {
if (!hasSubscriptionFields(data || diff)) {
return;
}

// Override data cuz we do not publish all fields
const subscription = await Subscriptions.findOneById(id, { projection: subscriptionFields });
if (!subscription) {
Expand Down Expand Up @@ -283,12 +302,16 @@ export function initWatchers(models: IModelsParam, broadcast: BroadcastCallback,
broadcast('watch.settings', { clientAction, setting });
});

watch<IRoom>(Rooms, async ({ clientAction, id, data }) => {
watch<IRoom>(Rooms, async ({ clientAction, id, data, diff }) => {
if (clientAction === 'removed') {
broadcast('watch.rooms', { clientAction, room: { _id: id } });
return;
}

if (!hasRoomFields(data || diff)) {
return;
}

const room = data ?? await Rooms.findOneById(id, { projection: roomFields });
if (!room) {
return;
Expand Down