Skip to content

Commit

Permalink
change 3 queries to use an aggregation
Browse files Browse the repository at this point in the history
  • Loading branch information
KevLehman committed Sep 2, 2024
1 parent f6be18a commit c80a40f
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 43 deletions.
1 change: 1 addition & 0 deletions apps/meteor/server/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import './models/startup';


Check failure on line 3 in apps/meteor/server/main.ts

View workflow job for this annotation

GitHub Actions / 🔎 Code Check / Code Lint

Delete `⏎`
/**
* ./settings uses top level await, in theory the settings creation
* and the startup should be done in parallel
Expand Down
96 changes: 78 additions & 18 deletions apps/meteor/server/models/raw/Rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1462,22 +1462,6 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.find({ uids: { $size: 2, $in: [uids] }, t: 'd' });
}

findPaginatedByNameOrFnameInIds(
ids: IRoom['_id'][],
filter?: string,
options: FindOptions<IRoom> = {},
): FindPaginated<FindCursor<IRoom>> {
const regxp = filter && new RegExp(escapeRegExp(filter), 'i');
const query: Filter<IRoom> = {
_id: {
$in: ids,
},
...(regxp && { $or: [{ name: regxp }, { fname: regxp }] }),
};

return this.findPaginated(query, options);
}

// UPDATE
addImportIds(_id: IRoom['_id'], importIds: string[]): Promise<UpdateResult> {
const query: Filter<IRoom> = { _id };
Expand Down Expand Up @@ -2076,7 +2060,83 @@ export class RoomsRaw extends BaseRaw<IRoom> implements IRoomsModel {
return this.updateMany(query, update);
}

findDiscussionsByPrid(prid: string, options?: FindOptions<IRoom>): FindCursor<IRoom> {
return this.find({ prid }, options);
findChildrenOfTeam(
teamId: string,
teamRoomId: string,
userId: string,
filter?: string,
options?: FindOptions<IRoom>,
): AggregationCursor<{ totalCount: { count: number }[]; paginatedResults: IRoom[] }> {
const nameFilter = filter ? new RegExp(escapeRegExp(filter), 'i') : undefined;
return this.col.aggregate<{ totalCount: { count: number }[]; paginatedResults: IRoom[] }>([
{
$match: {
$and: [
{
$or: [
{
teamId,
},
{ prid: teamRoomId },
],
},
...(nameFilter ? [{ $or: [{ fname: nameFilter }, { name: nameFilter }] }] : []),
],
},
},
{
$lookup: {
from: 'rocketchat_subscription',
let: {
roomId: '$_id',
},
pipeline: [
{
$match: {
$and: [
{
$expr: {
$eq: ['$rid', '$$roomId'],
},
},
{
$expr: {
$eq: ['$u._id', userId],
},
},
],
},
},
{
$project: { _id: 1 },
},
],
as: 'subscription',
},
},
{
$match: {
$or: [
{ t: 'c' },
{
$expr: {
$ne: [{ $size: '$subscription' }, 0],
},
},
],
},
},
{ $project: { subscription: 0 } },
{ $sort: options?.sort || { ts: 1 } },
{
$facet: {
totalCount: [{ $count: 'count' }],
paginatedResults: [
{ $skip: options?.skip || 0 }, // Replace 0 with your skip value
{ $limit: options?.limit || 50 }, // Replace 10 with your limit value
],
},
},
]);
}
}
26 changes: 4 additions & 22 deletions apps/meteor/server/services/team/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1069,30 +1069,12 @@ export class TeamService extends ServiceClassInternal implements ITeamService {
throw new Error('error-invalid-team-no-main-room');
}

const [discussionIds, teamRooms] = await Promise.all([
Rooms.findDiscussionsByPrid(mainRoom._id, { projection: { _id: 1 } })
.map(({ _id }) => _id)
.toArray(),
Rooms.findByTeamId(team._id, { projection: { _id: 1, t: 1 } }).toArray(),
]);

const teamPublicIds = teamRooms.filter(({ t }) => t === 'c').map(({ _id }) => _id);
const teamRoomIds = teamRooms.map(({ _id }) => _id);
const roomIds = await Subscriptions.findByUserIdAndRoomIds(userId, teamRoomIds, { projection: { rid: 1 } })
.map(({ rid }) => rid)
.toArray();

const { cursor, totalCount } = Rooms.findPaginatedByNameOrFnameInIds(
[...new Set([mainRoom._id, ...roomIds, ...discussionIds, ...teamPublicIds])],
filter,
const [
{
skip,
limit,
sort,
totalCount: [{ count: total }],
paginatedResults: data,
},
);

const [data, total] = await Promise.all([cursor.toArray(), totalCount]);
] = await Rooms.findChildrenOfTeam(team._id, mainRoom._id, userId, filter, { skip, limit, sort }).toArray();

return {
total,
Expand Down
10 changes: 7 additions & 3 deletions packages/model-typings/src/models/IRoomsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,6 @@ export interface IRoomsModel extends IBaseModel<IRoom> {

findSmallestFederatedRoomInNumberOfUsers(options?: FindOptions<IRoom>): Promise<IRoom | undefined>;

findPaginatedByNameOrFnameInIds(ids: IRoom['_id'][], filter?: string, options?: FindOptions<IRoom>): FindPaginated<FindCursor<IRoom>>;

countFederatedRooms(): Promise<number>;
incMsgCountById(rid: string, inc: number): Promise<UpdateResult>;
getIncMsgCountUpdateQuery(inc: number, roomUpdater: Updater<IRoom>): Updater<IRoom>;
Expand Down Expand Up @@ -283,5 +281,11 @@ export interface IRoomsModel extends IBaseModel<IRoom> {
getSubscribedRoomIdsWithoutE2EKeys(uid: IUser['_id']): Promise<IRoom['_id'][]>;
removeUsersFromE2EEQueueByRoomId(roomId: IRoom['_id'], uids: IUser['_id'][]): Promise<Document | UpdateResult>;
removeUserFromE2EEQueue(uid: IUser['_id']): Promise<Document | UpdateResult>;
findDiscussionsByPrid(prid: string, options?: FindOptions<IRoom>): FindCursor<IRoom>;
findChildrenOfTeam(
teamId: string,
teamRoomId: string,
userId: string,
filter?: string,
options?: FindOptions<IRoom>,
): AggregationCursor<{ totalCount: { count: number }[]; paginatedResults: IRoom[] }>;
}

0 comments on commit c80a40f

Please sign in to comment.