Skip to content

Commit

Permalink
Improve history performance (#605)
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed Feb 6, 2024
1 parent 9d9d071 commit f2ef7fc
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions src/plugins/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class HistoryRepository {
}

/**
* @param {object} filter
* @param {object|null} filter
* @param {{ offset?: number, limit?: number }} [pagination]
* @returns {Promise<Page<PopulatedHistoryEntry, { offset: number, limit: number }>>}
*/
Expand All @@ -43,12 +43,37 @@ class HistoryRepository {
MAX_PAGE_SIZE,
);

const total = await HistoryEntry.where(filter).countDocuments();
const query = HistoryEntry.where(filter)
.sort({ playedAt: -1 })
.skip(offset)
.limit(limit)
.populate('media.media user');
const total = await HistoryEntry.where(filter ?? {}).countDocuments();
/** @type {import('mongoose').PipelineStage[]} */
const aggregate = [];
if (filter != null) {
aggregate.push({ $match: filter });
}
aggregate.push(
{ $sort: { playedAt: -1 } },
{ $skip: offset },
{ $limit: limit },
{
$lookup: {
from: 'media',
localField: 'media.media',
foreignField: '_id',
as: 'media.media',
},
},
{ $unwind: '$media.media' },
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{ $unwind: '$user' },
{ $project: { __v: 0, 'media.media.__v': 0, 'user.__v': 0 } },
);
const query = HistoryEntry.aggregate(aggregate);

/** @type {PopulatedHistoryEntry[]} */
const results = /** @type {any} */ (await query);
Expand Down

0 comments on commit f2ef7fc

Please sign in to comment.