Refactored notifications from Check model to NetworkService

This commit is contained in:
Alex Holliday
2024-08-14 10:20:35 -07:00
parent a6116da278
commit 809e6ee58f
5 changed files with 59 additions and 129 deletions
+2 -61
View File
@@ -263,69 +263,10 @@ const getMonitorStatsById = async (req) => {
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorById = async (req, res) => {
const getMonitorById = async (monitorId) => {
try {
const { monitorId } = req.params;
let { status, limit, sortOrder, filter, numToDisplay, normalize } =
req.query;
const filterLookup = {
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
};
// This effectively removes limit, returning all checks
if (limit === undefined) limit = 0;
// Default sort order is newest -> oldest
if (sortOrder === "asc") {
sortOrder = 1;
} else if (sortOrder === "desc") {
sortOrder = -1;
} else sortOrder = -1;
const monitor = await Monitor.findById(monitorId);
const checksQuery = { monitorId: monitor._id };
if (status !== undefined) {
checksQuery.status = status;
}
// Filter checks by "day", "week", or "month"
if (filter !== undefined) {
checksQuery.createdAt = { $gte: filterLookup[filter] };
}
// Determine model type
let model =
monitor.type === "http" || monitor.type === "ping"
? Check
: PageSpeedCheck;
let checks = await model
.find(checksQuery)
.sort({
createdAt: sortOrder,
})
.limit(limit);
// If more than numToDisplay checks, pick every nth check
if (numToDisplay !== undefined && checks && checks.length > numToDisplay) {
const n = Math.ceil(checks.length / numToDisplay);
checks = checks.filter(
(_, index) => index % n === 0 || index === checks.length - 1
);
}
// Normalize checks if requested
if (normalize !== undefined) {
checks = NormalizeData(checks, 1, 100);
}
const notifications = await Notification.find({ monitorId: monitor._id });
const monitorWithChecks = { ...monitor.toObject(), checks, notifications };
return monitorWithChecks;
return monitor;
} catch (error) {
throw error;
}