From 33e88642b3fac433a5d5231f2b3c767552cfb520 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 6 Nov 2024 11:17:08 +0800 Subject: [PATCH] Add db method for getAllMonitorsWithUptimeStats --- Server/db/mongo/modules/monitorModule.js | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Server/db/mongo/modules/monitorModule.js b/Server/db/mongo/modules/monitorModule.js index 2a692596e..826f14d49 100644 --- a/Server/db/mongo/modules/monitorModule.js +++ b/Server/db/mongo/modules/monitorModule.js @@ -43,6 +43,53 @@ const getAllMonitors = async (req, res) => { } }; +/** + * Get all monitors with uptime stats for 1,7,30, and 90 days + * @async + * @param {Express.Request} req + * @param {Express.Response} res + * @returns {Promise>} + * @throws {Error} + */ +const getAllMonitorsWithUptimeStats = async () => { + const timeRanges = { + 1: new Date(Date.now() - 24 * 60 * 60 * 1000), + 7: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), + 30: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), + 90: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000), + }; + + try { + const monitors = await Monitor.find(); + const monitorsWithStats = await Promise.all( + monitors.map(async (monitor) => { + const model = CHECK_MODEL_LOOKUP[monitor.type]; + + const uptimeStats = await Promise.all( + Object.entries(timeRanges).map(async ([days, startDate]) => { + const checks = await model.find({ + monitorId: monitor._id, + createdAt: { $gte: startDate }, + }); + return [days, getUptimePercentage(checks)]; + }) + ); + + return { + ...monitor.toObject(), + ...Object.fromEntries(uptimeStats), + }; + }) + ); + + return monitorsWithStats; + } catch (error) { + error.service = SERVICE_NAME; + error.method = "getAllMonitorsWithUptimeStats"; + throw error; + } +}; + /** * Function to calculate uptime duration based on the most recent check. * @param {Array} checks Array of check objects. @@ -594,6 +641,7 @@ const addDemoMonitors = async (userId, teamId) => { export { getAllMonitors, + getAllMonitorsWithUptimeStats, getMonitorStatsById, getMonitorById, getMonitorsAndSummaryByTeamId,