status page service/repo refactor

This commit is contained in:
Alex Holliday committed 2026-01-22 20:57:20 +00:00
1 parent 2359255ef7
commit e6c268f14e
18 files changed
+357 -47

No files matched your search

@@ -1,4 +1,4 @@
import { type MonitorType, type Monitor, type MonitorsSummary } from "@/types/index.js";
import { type MonitorType, type Monitor, type MonitorsSummary, type MonitorWithChecks } from "@/types/index.js";
export interface TeamQueryConfig {
limit?: number;
@@ -25,6 +25,7 @@ export interface IMonitorsRepository {
findAll(): Promise<Monitor[] | null>;
findByTeamId(teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null>;
findByIds(monitorIds: string[]): Promise<Monitor[]>;
findByIdsWithChecks(monitorIds: string[], checksCount?: number): Promise<MonitorWithChecks[]>;
// update
updateById(monitorId: string, teamId: string, updates: Partial<Monitor>): Promise<Monitor>;
@@ -1,7 +1,7 @@
import { MonitorModel } from "@/db/models/index.js";
import type { MonitorDocument } from "@/db/models/index.js";
import type { Monitor, MonitorsSummary } from "@/types/index.js";
import mongoose, { type FilterQuery } from "mongoose";
import type { Monitor, MonitorsSummary, MonitorWithChecks, Check } from "@/types/index.js";
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
import type { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "./IMonitorsRepository.js";
import { AppError } from "@/utils/AppError.js";
@@ -79,6 +79,78 @@ class MongoMonitorsRepository implements IMonitorsRepository {
return this.mapDocuments(monitors);
};
findByIdsWithChecks = async (monitorIds: string[], checksCount: number = 25): Promise<MonitorWithChecks[]> => {
if (!monitorIds.length) {
return [];
}
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
const pipeline: PipelineStage[] = [
{ $match: { _id: { $in: objectIds } } },
{
$lookup: {
from: "checks",
let: { monitorId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$metadata.monitorId", "$$monitorId"] } } },
{ $sort: { createdAt: -1 } },
{ $limit: checksCount },
],
as: "checks",
},
},
{
$lookup: {
from: "maintenancewindows",
let: { monitorId: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$monitorId", "$$monitorId"] } } }],
as: "maintenanceWindows",
},
},
{
$lookup: {
from: "monitorstats",
localField: "_id",
foreignField: "monitorId",
as: "stats",
},
},
{
$addFields: {
isMaintenance: {
$reduce: {
input: "$maintenanceWindows",
initialValue: false,
in: {
$or: [
"$$value",
{
$and: [
{ $eq: ["$$this.active", true] },
{ $lte: ["$$this.start", "$$NOW"] },
{ $gte: ["$$this.end", "$$NOW"] },
],
},
],
},
},
},
uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] },
},
},
{
$project: {
maintenanceWindows: 0,
stats: 0,
},
},
];
const documents = await MonitorModel.aggregate(pipeline);
return documents.map((doc) => this.toEntityWithChecks(doc));
};
findMonitorCountByTeamIdAndType = async (teamId: string, config?: TeamQueryConfig): Promise<number> => {
const { type } = config ?? {};
@@ -249,6 +321,90 @@ class MongoMonitorsRepository implements IMonitorsRepository {
updatedAt: toDateString(doc.updatedAt),
};
};
private toEntityWithChecks = (doc: any): MonitorWithChecks => {
const toStringId = (value: unknown): string => {
if (value instanceof mongoose.Types.ObjectId) {
return value.toString();
}
return value?.toString() ?? "";
};
const toDateString = (value: Date | string): string => {
if (!value) return "";
return value instanceof Date ? value.toISOString() : value;
};
const notificationIds = (doc.notifications ?? []).map((notification: unknown) => toStringId(notification));
const checks: Check[] = (doc.checks ?? []).map((check: any) => ({
id: toStringId(check._id),
metadata: {
monitorId: toStringId(check.metadata?.monitorId),
teamId: toStringId(check.metadata?.teamId),
type: check.metadata?.type,
},
status: check.status,
responseTime: check.responseTime,
timings: check.timings,
statusCode: check.statusCode,
message: check.message,
ack: check.ack,
ackAt: check.ackAt ?? null,
expiry: toDateString(check.expiry),
cpu: check.cpu,
memory: check.memory,
disk: check.disk,
host: check.host,
errors: check.errors,
capture: check.capture,
net: check.net,
accessibility: check.accessibility,
bestPractices: check.bestPractices,
seo: check.seo,
performance: check.performance,
audits: check.audits,
__v: check.__v,
createdAt: toDateString(check.createdAt),
updatedAt: toDateString(check.updatedAt),
}));
return {
id: toStringId(doc._id),
userId: toStringId(doc.userId),
teamId: toStringId(doc.teamId),
name: doc.name,
description: doc.description ?? undefined,
status: doc.status ?? undefined,
statusWindow: doc.statusWindow ?? [],
statusWindowSize: doc.statusWindowSize,
statusWindowThreshold: doc.statusWindowThreshold,
type: doc.type,
ignoreTlsErrors: doc.ignoreTlsErrors,
jsonPath: doc.jsonPath ?? undefined,
expectedValue: doc.expectedValue ?? undefined,
matchMethod: doc.matchMethod ?? undefined,
url: doc.url,
port: doc.port ?? undefined,
isActive: doc.isActive,
interval: doc.interval,
uptimePercentage: doc.uptimePercentage ?? undefined,
notifications: notificationIds,
secret: doc.secret ?? undefined,
thresholds: doc.thresholds ?? undefined,
alertThreshold: doc.alertThreshold,
cpuAlertThreshold: doc.cpuAlertThreshold,
memoryAlertThreshold: doc.memoryAlertThreshold,
diskAlertThreshold: doc.diskAlertThreshold,
tempAlertThreshold: doc.tempAlertThreshold,
selectedDisks: doc.selectedDisks ?? [],
gameId: doc.gameId ?? undefined,
group: doc.group ?? null,
createdAt: toDateString(doc.createdAt),
updatedAt: toDateString(doc.updatedAt),
checks,
};
};
}
export default MongoMonitorsRepository;
@@ -2,10 +2,15 @@ import type { StatusPage } from "@/types/statusPage.js";
export interface IStatusPagesRepository {
// create
create(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
// single fetch
findByUrl(url: string): Promise<StatusPage>;
findByTeamId(teamId: string): Promise<StatusPage[]>;
// collection fetch
// update
updateById(id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
// delete
deleteById(id: string, teamId: string): Promise<StatusPage>;
// other
removeMonitorFromStatusPages(monitorId: string): Promise<number>;
}
@@ -2,6 +2,7 @@ import { IStatusPagesRepository } from "@/repositories/index.js";
import { type StatusPageDocument, StatusPageModel } from "@/db/models/StatusPage.js";
import type { StatusPage, StatusPageLogo } from "@/types/statusPage.js";
import mongoose from "mongoose";
import { AppError } from "@/utils/AppError.js";
class MongoStatusPagesRepository implements IStatusPagesRepository {
private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => {
@@ -56,6 +57,74 @@ class MongoStatusPagesRepository implements IStatusPagesRepository {
};
};
private mapDocuments = (documents: StatusPageDocument[]): StatusPage[] => {
if (!documents?.length) {
return [];
}
return documents.map((doc) => this.toEntity(doc));
};
create = async (userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
const statusPage = new StatusPageModel({
...data,
userId,
teamId,
});
if (image) {
statusPage.logo = {
data: image.buffer,
contentType: image.mimetype,
};
}
await statusPage.save();
return this.toEntity(statusPage);
};
findByUrl = async (url: string): Promise<StatusPage> => {
const statusPage = await StatusPageModel.findOne({
url,
});
if (!statusPage) {
throw new AppError({ message: "Status page not found", status: 404 });
}
return this.toEntity(statusPage);
// Get status page
};
findByTeamId = async (teamId: string): Promise<StatusPage[]> => {
const statusPages = await StatusPageModel.find({ teamId });
return this.mapDocuments(statusPages);
};
updateById = async (id: string, teamId: string, image: Express.Multer.File | undefined, patch: Partial<StatusPage>): Promise<StatusPage> => {
if (image) {
patch.logo = {
data: image.buffer,
contentType: image.mimetype,
};
} else {
patch.logo = null;
}
const statusPage = await StatusPageModel.findOneAndUpdate({ teamId, _id: id }, patch, {
new: true,
});
if (!statusPage) {
throw new AppError({ message: "Status page not found", status: 404 });
}
return this.toEntity(statusPage);
};
deleteById = async (id: string, teamId: string): Promise<StatusPage> => {
const statusPage = await StatusPageModel.findOneAndDelete({ _id: id, teamId });
if (!statusPage) {
throw new AppError({ message: "Status page not found", status: 404 });
}
return this.toEntity(statusPage);
};
removeMonitorFromStatusPages = async (monitorId: string): Promise<number> => {
const res = await StatusPageModel.updateMany({ monitors: monitorId }, { $pull: { monitors: monitorId } });
return res.modifiedCount;