Skip to content

Commit

Permalink
use findOneAndDelete
Browse files Browse the repository at this point in the history
  • Loading branch information
sampaiodiego committed Aug 20, 2024
1 parent 620acd5 commit ab8c87a
Show file tree
Hide file tree
Showing 10 changed files with 66 additions and 31 deletions.
8 changes: 3 additions & 5 deletions apps/meteor/app/federation/server/endpoints/dispatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import {
notifyOnMessageChange,
notifyOnRoomChanged,
notifyOnRoomChangedById,
notifyOnSubscriptionChanged,
notifyOnSubscriptionChangedById,
notifyOnSubscriptionChangedByRoomIdAndUserId,
} from '../../../lib/server/lib/notifyListener';
import { notifyUsersOnMessage } from '../../../lib/server/lib/notifyUsersOnMessage';
import { sendAllNotifications } from '../../../lib/server/lib/sendNotificationsOnMessage';
Expand Down Expand Up @@ -186,9 +186,8 @@ const eventHandlers = {

// Remove the user's subscription
const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(roomId, user._id);

if (deletedSubscription) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(roomId, user._id, 'removed');
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}

// Refresh the servers list
Expand Down Expand Up @@ -218,9 +217,8 @@ const eventHandlers = {

// Remove the user's subscription
const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(roomId, user._id);

if (deletedSubscription) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(roomId, user._id, 'removed');
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}

// Refresh the servers list
Expand Down
5 changes: 2 additions & 3 deletions apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Meteor } from 'meteor/meteor';
import { afterLeaveRoomCallback } from '../../../../lib/callbacks/afterLeaveRoomCallback';
import { beforeLeaveRoomCallback } from '../../../../lib/callbacks/beforeLeaveRoomCallback';
import { settings } from '../../../settings/server';
import { notifyOnRoomChangedById, notifyOnSubscriptionChangedByRoomIdAndUserId } from '../lib/notifyListener';
import { notifyOnRoomChangedById, notifyOnSubscriptionChanged } from '../lib/notifyListener';

export const removeUserFromRoom = async function (rid: string, user: IUser, options?: { byUser: IUser }): Promise<void> {
const room = await Rooms.findOneById(rid);
Expand Down Expand Up @@ -57,9 +57,8 @@ export const removeUserFromRoom = async function (rid: string, user: IUser, opti
}

const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(rid, user._id);

if (deletedSubscription) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(rid, user._id, 'removed');
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}

if (room.teamId && room.teamMain) {
Expand Down
17 changes: 7 additions & 10 deletions apps/meteor/app/lib/server/lib/notifyListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,21 +472,18 @@ export const notifyOnMessageChange = withDbWatcherCheck(async ({ id, data }: { i
});

export const notifyOnSubscriptionChanged = withDbWatcherCheck(
async (subscription: ISubscription, clientAction: Exclude<ClientAction, 'removed'> = 'updated'): Promise<void> => {
async (subscription: ISubscription, clientAction: ClientAction = 'updated'): Promise<void> => {
void api.broadcast('watch.subscriptions', { clientAction, subscription });
},
);

export const notifyOnSubscriptionChangedByRoomIdAndUserId = withDbWatcherCheck(
async (rid: ISubscription['rid'], uid: ISubscription['u']['_id'], clientAction: ClientAction = 'updated'): Promise<void> => {
const subscriptions =
clientAction === 'removed'
? Subscriptions.trashFind({ rid, 'u._id': uid }, { projection: subscriptionFields })
: Subscriptions.findByUserIdAndRoomIds(uid, [rid], { projection: subscriptionFields });

if (!subscriptions) {
return;
}
async (
rid: ISubscription['rid'],
uid: ISubscription['u']['_id'],
clientAction: Exclude<ClientAction, 'removed'> = 'updated',
): Promise<void> => {
const subscriptions = Subscriptions.findByUserIdAndRoomIds(uid, [rid], { projection: subscriptionFields });

for await (const subscription of subscriptions) {
void api.broadcast('watch.subscriptions', { clientAction, subscription });
Expand Down
5 changes: 2 additions & 3 deletions apps/meteor/app/livechat/server/lib/Helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
notifyOnLivechatDepartmentAgentChangedByAgentsAndDepartmentId,
notifyOnSubscriptionChangedById,
notifyOnSubscriptionChangedByRoomId,
notifyOnSubscriptionChangedByRoomIdAndUserId,
notifyOnSubscriptionChanged,
} from '../../../lib/server/lib/notifyListener';
import { settings } from '../../../settings/server';
import { Livechat as LivechatTyped } from './LivechatTyped';
Expand Down Expand Up @@ -306,9 +306,8 @@ export const removeAgentFromSubscription = async (rid: string, { _id, username }
}

const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(rid, _id);

if (deletedSubscription) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(rid, _id, 'removed');
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}

await Message.saveSystemMessage('ul', rid, username || '', { _id: user._id, username: user.username, name: user.name });
Expand Down
8 changes: 5 additions & 3 deletions apps/meteor/server/methods/removeUserFromRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import { Meteor } from 'meteor/meteor';
import { canAccessRoomAsync, getUsersInRole } from '../../app/authorization/server';
import { hasPermissionAsync } from '../../app/authorization/server/functions/hasPermission';
import { hasRoleAsync } from '../../app/authorization/server/functions/hasRole';
import { notifyOnRoomChanged, notifyOnSubscriptionChangedByRoomIdAndUserId } from '../../app/lib/server/lib/notifyListener';
import {
notifyOnRoomChanged,
notifyOnSubscriptionChanged,
} from '../../app/lib/server/lib/notifyListener';
import { settings } from '../../app/settings/server';
import { RoomMemberActions } from '../../definition/IRoomTypeConfig';
import { callbacks } from '../../lib/callbacks';
Expand Down Expand Up @@ -90,9 +93,8 @@ export const removeUserFromRoomMethod = async (fromId: string, data: { rid: stri
await callbacks.run('beforeRemoveFromRoom', { removedUser, userWhoRemoved: fromUser }, room);

const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(data.rid, removedUser._id);

if (deletedSubscription) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(data.rid, removedUser._id, 'removed');
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}

if (['c', 'p'].includes(room.t) === true) {
Expand Down
7 changes: 7 additions & 0 deletions apps/meteor/server/models/dummy/BaseDummy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ export class BaseDummy<
return this.collectionName;
}

async findOneAndDelete(): Promise<ModifyResult<T>> {
return {
value: null,
ok: 1,
};
}

async findOneAndUpdate(): Promise<ModifyResult<T>> {
return {
value: null,
Expand Down
33 changes: 32 additions & 1 deletion apps/meteor/server/models/raw/BaseRaw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type {
InsertOneResult,
DeleteResult,
DeleteOptions,
FindOneAndDeleteOptions,
} from 'mongodb';

import { setUpdatedAt } from './setUpdatedAt';
Expand Down Expand Up @@ -315,7 +316,37 @@ export abstract class BaseRaw<
return this.col.deleteOne(filter);
}

async deleteMany(filter: Filter<T>, options?: DeleteOptions): Promise<DeleteResult> {
async findOneAndDelete(filter: Filter<T>, options?: FindOneAndDeleteOptions): Promise<ModifyResult<T>> {
if (!this.trash) {
if (options) {
return this.col.findOneAndDelete(filter, options);
}
return this.col.findOneAndDelete(filter);
}

const result = await this.col.findOneAndDelete(filter);

const { value: doc } = result;
if (!doc) {
return result;
}

const { _id, ...record } = doc;

const trash: TDeleted = {
...record,
_deletedAt: new Date(),
__collection__: this.name,
} as unknown as TDeleted;

// since the operation is not atomic, we need to make sure that the record is not already deleted/inserted
await this.trash?.updateOne({ _id } as Filter<TDeleted>, { $set: trash } as UpdateFilter<TDeleted>, {
upsert: true,
});

return result;
}

if (!this.trash) {
if (options) {
return this.col.deleteMany(filter, options);
Expand Down
10 changes: 5 additions & 5 deletions apps/meteor/server/models/raw/Subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1848,21 +1848,21 @@ export class SubscriptionsRaw extends BaseRaw<ISubscription> implements ISubscri
return result;
}

async removeByRoomIdAndUserId(roomId: string, userId: string): Promise<number> {
async removeByRoomIdAndUserId(roomId: string, userId: string): Promise<ISubscription | null> {
const query = {
'rid': roomId,
'u._id': userId,
};

const result = (await this.deleteMany(query)).deletedCount;
const { value: doc } = await this.findOneAndDelete(query);

if (typeof result === 'number' && result > 0) {
await Rooms.incUsersCountById(roomId, -result);
if (doc) {
await Rooms.incUsersCountById(roomId, -1);
}

await Users.removeRoomByUserId(userId, roomId);

return result;
return doc;
}

async removeByRoomIds(rids: string[]): Promise<DeleteResult> {
Expand Down
2 changes: 2 additions & 0 deletions packages/model-typings/src/models/IBaseModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
EnhancedOmit,
Filter,
FindCursor,
FindOneAndDeleteOptions,
FindOneAndUpdateOptions,
FindOptions,
InsertManyResult,
Expand Down Expand Up @@ -53,6 +54,7 @@ export interface IBaseModel<
getUpdater(): Updater<T>;
updateFromUpdater(query: Filter<T>, updater: Updater<T>): Promise<UpdateResult>;

findOneAndDelete(filter: Filter<T>, options?: FindOneAndDeleteOptions): Promise<ModifyResult<T>>;
findOneAndUpdate(query: Filter<T>, update: UpdateFilter<T> | T, options?: FindOneAndUpdateOptions): Promise<ModifyResult<T>>;

findOneById(_id: T['_id'], options?: FindOptions<T> | undefined): Promise<T | null>;
Expand Down
2 changes: 1 addition & 1 deletion packages/model-typings/src/models/ISubscriptionsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ export interface ISubscriptionsModel extends IBaseModel<ISubscription> {
users: { user: AtLeast<IUser, '_id' | 'username' | 'name' | 'settings'>; extraData: Record<string, any> }[],
): Promise<InsertManyResult<ISubscription>>;
removeByRoomIdsAndUserId(rids: string[], userId: string): Promise<number>;
removeByRoomIdAndUserId(roomId: string, userId: string): Promise<number>;
removeByRoomIdAndUserId(roomId: string, userId: string): Promise<ISubscription | null>;

removeByRoomIds(rids: string[]): Promise<DeleteResult>;

Expand Down

0 comments on commit ab8c87a

Please sign in to comment.