Merge branch 'develop' into feat/bulk-edit-notifications
This commit is contained in:
42 files changed
+378
-156
No files matched your search
@@ -23,7 +23,24 @@ import { IUserService } from "@/service/index.js";
|
|||||||
|
|
||||||
const SERVICE_NAME = "authController";
|
const SERVICE_NAME = "authController";
|
||||||
|
|
||||||
class AuthController {
|
export interface IAuthController {
|
||||||
|
registerUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
createUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
loginUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
editUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
checkSuperadminExists(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
requestRecovery(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
validateRecovery(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
resetPassword(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
deleteUser(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
deleteUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
getAllUsers(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
getUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
editUserById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
editUserPasswordById(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuthController implements IAuthController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private userService: IUserService;
|
private userService: IUserService;
|
||||||
|
|||||||
@@ -12,7 +12,16 @@ import { requireTeamId } from "@/controllers/controllerUtils.js";
|
|||||||
|
|
||||||
const SERVICE_NAME = "checkController";
|
const SERVICE_NAME = "checkController";
|
||||||
|
|
||||||
class CheckController {
|
export interface ICheckController {
|
||||||
|
serviceName: string;
|
||||||
|
getChecksByMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getChecksByTeam: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getChecksSummaryByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteChecks: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteChecksByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class CheckController implements ICheckController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private checkService: ICheckService;
|
private checkService: ICheckService;
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { IDiagnosticService } from "@/service/index.js";
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
const SERVICE_NAME = "diagnosticController";
|
const SERVICE_NAME = "diagnosticController";
|
||||||
class DiagnosticController {
|
|
||||||
|
export interface IDiagnosticController {
|
||||||
|
getSystemStats: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class DiagnosticController implements IDiagnosticController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private diagnosticService: IDiagnosticService;
|
private diagnosticService: IDiagnosticService;
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { getChecksParamValidation, getChecksQueryValidation } from "@/validation/checkValidation.js";
|
import { getChecksParamValidation, getChecksQueryValidation } from "@/validation/checkValidation.js";
|
||||||
import type { IGeoChecksService } from "@/service/business/geoChecksService.js";
|
import type { IGeoChecksService } from "@/service/business/geoChecksService.js";
|
||||||
|
import { requireTeamId } from "./controllerUtils.js";
|
||||||
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "geoCheckController";
|
const SERVICE_NAME = "geoCheckController";
|
||||||
|
|
||||||
class GeoCheckController {
|
export interface IGeoCheckController {
|
||||||
|
getGeoChecksByMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
class GeoCheckController implements IGeoCheckController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private geoChecksService: IGeoChecksService;
|
private geoChecksService: IGeoChecksService;
|
||||||
@@ -18,13 +23,29 @@ class GeoCheckController {
|
|||||||
|
|
||||||
getGeoChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
getGeoChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
getChecksParamValidation.parse(req.params);
|
const validatedParams = getChecksParamValidation.parse(req.params);
|
||||||
getChecksQueryValidation.parse(req.query);
|
const validatedQuery = getChecksQueryValidation.parse(req.query);
|
||||||
|
|
||||||
|
if (!validatedQuery.continent || validatedQuery.continent.length === 0) {
|
||||||
|
throw new AppError({
|
||||||
|
message: "At least one continent must be specified",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "getGeoChecksByMonitor",
|
||||||
|
details: { monitorId: validatedParams.monitorId },
|
||||||
|
status: 400,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const result = await this.geoChecksService.getGeoChecksByMonitor({
|
const result = await this.geoChecksService.getGeoChecksByMonitor({
|
||||||
monitorId: req?.params?.monitorId as string,
|
monitorId: validatedParams.monitorId,
|
||||||
query: req?.query,
|
teamId: teamId,
|
||||||
teamId: req?.user?.teamId as string,
|
sortOrder: validatedQuery.sortOrder,
|
||||||
|
dateRange: validatedQuery.dateRange,
|
||||||
|
page: validatedQuery.page,
|
||||||
|
rowsPerPage: validatedQuery.rowsPerPage,
|
||||||
|
continent: validatedQuery.continent,
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
|
|||||||
@@ -5,7 +5,14 @@ import { IIncidentService } from "@/service/index.js";
|
|||||||
import { getIncidentsByTeamQueryValidation, getIncidentSummaryQueryValidation } from "@/validation/incidentValidation.js";
|
import { getIncidentsByTeamQueryValidation, getIncidentSummaryQueryValidation } from "@/validation/incidentValidation.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "IncidentController";
|
const SERVICE_NAME = "IncidentController";
|
||||||
class IncidentController {
|
|
||||||
|
export interface IIncidentController {
|
||||||
|
getIncidentsByTeam: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getIncidentSummary: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getIncidentById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
resolveIncidentManually: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
class IncidentController implements IIncidentController {
|
||||||
private incidentService: IIncidentService;
|
private incidentService: IIncidentService;
|
||||||
constructor(incidentService: IIncidentService) {
|
constructor(incidentService: IIncidentService) {
|
||||||
this.incidentService = incidentService;
|
this.incidentService = incidentService;
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ import { requireFirstName, requireTeamId, requireUserRoles } from "@/controllers
|
|||||||
import { IInviteService } from "@/service/index.js";
|
import { IInviteService } from "@/service/index.js";
|
||||||
const SERVICE_NAME = "inviteController";
|
const SERVICE_NAME = "inviteController";
|
||||||
|
|
||||||
class InviteController {
|
export interface IInviteController {
|
||||||
|
getInviteToken: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
sendInviteEmail: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
verifyInviteToken: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class InviteController implements IInviteController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private inviteService: IInviteService;
|
private inviteService: IInviteService;
|
||||||
constructor(inviteService: IInviteService) {
|
constructor(inviteService: IInviteService) {
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
|
|
||||||
const SERVICE_NAME = "LogController";
|
const SERVICE_NAME = "LogController";
|
||||||
|
|
||||||
|
export interface ILogController {
|
||||||
|
getLogs: (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
class LogController {
|
class LogController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private logger: ILogger;
|
private logger: ILogger;
|
||||||
|
|||||||
@@ -11,7 +11,15 @@ import {
|
|||||||
import { requireTeamId } from "@/controllers/controllerUtils.js";
|
import { requireTeamId } from "@/controllers/controllerUtils.js";
|
||||||
import { IMaintenanceWindowService } from "@/service/index.js";
|
import { IMaintenanceWindowService } from "@/service/index.js";
|
||||||
|
|
||||||
class MaintenanceWindowController {
|
export interface IMaintenanceWindowController {
|
||||||
|
createMaintenanceWindows: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMaintenanceWindowById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMaintenanceWindowsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMaintenanceWindowsByMonitorId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteMaintenanceWindow: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
editMaintenanceWindow: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
class MaintenanceWindowController implements IMaintenanceWindowController {
|
||||||
private maintenanceWindowService: IMaintenanceWindowService;
|
private maintenanceWindowService: IMaintenanceWindowService;
|
||||||
constructor(maintenanceWindowService: IMaintenanceWindowService) {
|
constructor(maintenanceWindowService: IMaintenanceWindowService) {
|
||||||
this.maintenanceWindowService = maintenanceWindowService;
|
this.maintenanceWindowService = maintenanceWindowService;
|
||||||
@@ -21,7 +29,17 @@ class MaintenanceWindowController {
|
|||||||
try {
|
try {
|
||||||
const validatedBody = createMaintenanceWindowBodyValidation.parse(req.body);
|
const validatedBody = createMaintenanceWindowBodyValidation.parse(req.body);
|
||||||
const teamId = requireTeamId(req?.user?.teamId);
|
const teamId = requireTeamId(req?.user?.teamId);
|
||||||
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, body: validatedBody });
|
|
||||||
|
const monitorIDs = validatedBody.monitors;
|
||||||
|
const name = validatedBody.name;
|
||||||
|
const active = validatedBody.active ?? true;
|
||||||
|
const duration = validatedBody.duration;
|
||||||
|
const durationUnit = validatedBody.durationUnit;
|
||||||
|
const repeat = validatedBody.repeat;
|
||||||
|
const start = validatedBody.start;
|
||||||
|
const end = validatedBody.end;
|
||||||
|
|
||||||
|
await this.maintenanceWindowService.createMaintenanceWindow({ teamId, monitorIDs, name, active, duration, durationUnit, repeat, start, end });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -20,9 +20,31 @@ import { fetchMonitorCertificate, requireTeamId, requireUserId } from "./control
|
|||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { IMonitorService, INotificationsService } from "@/service/index.js";
|
import { IMonitorService, INotificationsService } from "@/service/index.js";
|
||||||
import { GeoContinent } from "@/types/geoCheck.js";
|
import { GeoContinent } from "@/types/geoCheck.js";
|
||||||
|
import { fetchMonitorCertificate, requireTeamId, requireUserId } from "@/controllers/controllerUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "monitorController";
|
const SERVICE_NAME = "monitorController";
|
||||||
class MonitorController {
|
|
||||||
|
export interface IMonitorController {
|
||||||
|
getMonitorCertificate: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getUptimeDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getHardwareDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getPageSpeedDetailsById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getGeoChecksByMonitorId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMonitorById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
createMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
importMonitorsFromJSON: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteAllMonitors: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
editMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
pauseMonitor: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
addDemoMonitors: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMonitorsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getMonitorsWithChecksByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
exportMonitorsToJSON: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getAllGames: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getGroupsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
class MonitorController implements IMonitorController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private monitorService: IMonitorService;
|
private monitorService: IMonitorService;
|
||||||
|
|||||||
@@ -15,7 +15,16 @@ import { IMonitorsRepository } from "@/repositories/index.js";
|
|||||||
|
|
||||||
const SERVICE_NAME = "NotificationController";
|
const SERVICE_NAME = "NotificationController";
|
||||||
|
|
||||||
class NotificationController {
|
export interface INotificationController {
|
||||||
|
testNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
createNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getNotificationsByTeamId: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
deleteNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
getNotificationById: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
editNotification: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
testAllNotifications: (req: Request, res: Response, next: NextFunction) => Promise<Response | void>;
|
||||||
|
}
|
||||||
|
class NotificationController implements INotificationController {
|
||||||
private notificationsService: INotificationsService;
|
private notificationsService: INotificationsService;
|
||||||
private monitorsRepository: IMonitorsRepository;
|
private monitorsRepository: IMonitorsRepository;
|
||||||
constructor(notificationsService: INotificationsService, monitorsRepository: IMonitorsRepository) {
|
constructor(notificationsService: INotificationsService, monitorsRepository: IMonitorsRepository) {
|
||||||
|
|||||||
@@ -3,7 +3,14 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
|
|
||||||
const SERVICE_NAME = "JobQueueController";
|
const SERVICE_NAME = "JobQueueController";
|
||||||
|
|
||||||
class JobQueueController {
|
export interface IJobQueueController {
|
||||||
|
getMetrics(req: Request, res: Response, next: NextFunction): Promise<void>;
|
||||||
|
getJobs(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
getAllMetrics(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
flushQueue(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class JobQueueController implements IJobQueueController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private jobQueue: ISuperSimpleQueue;
|
private jobQueue: ISuperSimpleQueue;
|
||||||
constructor(jobQueue: ISuperSimpleQueue) {
|
constructor(jobQueue: ISuperSimpleQueue) {
|
||||||
|
|||||||
@@ -6,7 +6,14 @@ import { IEmailService, ISettingsService } from "@/service/index.js";
|
|||||||
|
|
||||||
const SERVICE_NAME = "SettingsController";
|
const SERVICE_NAME = "SettingsController";
|
||||||
|
|
||||||
class SettingsController {
|
export interface ISettingsController {
|
||||||
|
serviceName: string;
|
||||||
|
getAppSettings(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
updateAppSettings(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
sendTestEmail(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class SettingsController implements ISettingsController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private settingsService: ISettingsService;
|
private settingsService: ISettingsService;
|
||||||
private emailService: IEmailService;
|
private emailService: IEmailService;
|
||||||
|
|||||||
@@ -15,7 +15,16 @@ import { NormalizeData } from "@/utils/dataUtils.js";
|
|||||||
|
|
||||||
const SERVICE_NAME = "statusPageController";
|
const SERVICE_NAME = "statusPageController";
|
||||||
|
|
||||||
class StatusPageController {
|
export interface IStatusPageController {
|
||||||
|
readonly serviceName: string;
|
||||||
|
createStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
updateStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
getStatusPageByUrl(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
getStatusPagesByTeamId(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
deleteStatusPage(req: Request, res: Response, next: NextFunction): Promise<Response | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class StatusPageController implements IStatusPageController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
private statusPageService: IStatusPageService;
|
private statusPageService: IStatusPageService;
|
||||||
private monitorsRepository: IMonitorsRepository;
|
private monitorsRepository: IMonitorsRepository;
|
||||||
@@ -66,7 +75,7 @@ class StatusPageController {
|
|||||||
if (statusPage === null) {
|
if (statusPage === null) {
|
||||||
throw new AppError({ message: "Status page not found", status: 404 });
|
throw new AppError({ message: "Status page not found", status: 404 });
|
||||||
}
|
}
|
||||||
return res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Status page updated successfully",
|
msg: "Status page updated successfully",
|
||||||
data: statusPage,
|
data: statusPage,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
|
import type { Document, AnyBulkWriteOperation } from "mongodb";
|
||||||
|
|
||||||
const CHECKS_COLLECTION = "checks";
|
const CHECKS_COLLECTION = "checks";
|
||||||
const BACKUP_COLLECTION = "checks_backup";
|
const BACKUP_COLLECTION = "checks_backup";
|
||||||
@@ -85,7 +86,7 @@ const createTimeSeriesCollection = async (backedUp: boolean) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const validateDocument = (doc: any): boolean => {
|
const validateDocument = (doc: Document): boolean => {
|
||||||
if (!doc.createdAt) {
|
if (!doc.createdAt) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -95,7 +96,7 @@ const validateDocument = (doc: any): boolean => {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const storeFailedDocument = async (doc: any, reason: string) => {
|
const storeFailedDocument = async (doc: Document, reason: string) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
await db.collection(FAILED_DOCS_COLLECTION).insertOne({
|
await db.collection(FAILED_DOCS_COLLECTION).insertOne({
|
||||||
originalDoc: doc,
|
originalDoc: doc,
|
||||||
@@ -124,8 +125,8 @@ const migrateBackupData = async (backedUp: boolean): Promise<MigrationStats> =>
|
|||||||
stats.totalSource = await source.countDocuments();
|
stats.totalSource = await source.countDocuments();
|
||||||
|
|
||||||
const cursor = source.find().addCursorFlag("noCursorTimeout", true);
|
const cursor = source.find().addCursorFlag("noCursorTimeout", true);
|
||||||
const operations: any[] = [];
|
const operations: AnyBulkWriteOperation<Document>[] = [];
|
||||||
const invalidDocs: any[] = [];
|
const invalidDocs: Document[] = [];
|
||||||
|
|
||||||
while (await cursor.hasNext()) {
|
while (await cursor.hasNext()) {
|
||||||
const doc = await cursor.next();
|
const doc = await cursor.next();
|
||||||
@@ -139,6 +140,7 @@ const migrateBackupData = async (backedUp: boolean): Promise<MigrationStats> =>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { _id, monitorId, teamId, type, ...rest } = doc;
|
const { _id, monitorId, teamId, type, ...rest } = doc;
|
||||||
|
void _id;
|
||||||
const metadata = { monitorId, teamId, type };
|
const metadata = { monitorId, teamId, type };
|
||||||
operations.push({ insertOne: { document: { ...rest, metadata } } });
|
operations.push({ insertOne: { document: { ...rest, metadata } } });
|
||||||
|
|
||||||
|
|||||||
@@ -42,10 +42,10 @@ export async function cleanupDuplicateMonitorStats(): Promise<void> {
|
|||||||
const monitorId = duplicate._id;
|
const monitorId = duplicate._id;
|
||||||
const { ids, updatedAts } = duplicate;
|
const { ids, updatedAts } = duplicate;
|
||||||
|
|
||||||
type DocPair = { id: any; updatedAt: Date };
|
type DocPair = { id: string; updatedAt: Date };
|
||||||
|
|
||||||
// Create array of {id, updatedAt} pairs and sort by updatedAt descending
|
// Create array of {id, updatedAt} pairs and sort by updatedAt descending
|
||||||
const docs: DocPair[] = ids.map((id: any, index: number) => ({
|
const docs: DocPair[] = ids.map((id: string, index: number) => ({
|
||||||
id,
|
id,
|
||||||
updatedAt: updatedAts[index],
|
updatedAt: updatedAts[index],
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ export async function fixInfrastructureThresholds(): Promise<void> {
|
|||||||
const update: Record<string, number> = {};
|
const update: Record<string, number> = {};
|
||||||
|
|
||||||
for (const field of thresholdFields) {
|
for (const field of thresholdFields) {
|
||||||
if ((monitor as any)[field] === 0 || (monitor as any)[field] === 5) {
|
const value = monitor.get(field);
|
||||||
|
if (value === 0 || value === 5) {
|
||||||
update[field] = 100;
|
update[field] = 100;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { cleanupDuplicateMonitorStats } from "./0003_cleanupDuplicateMonitorStat
|
|||||||
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
||||||
import MigrationModel from "../models/Migration.js";
|
import MigrationModel from "../models/Migration.js";
|
||||||
import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js";
|
import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js";
|
||||||
|
import type { ILogger } from "@/utils/logger.js";
|
||||||
|
|
||||||
type MigrationEntry = {
|
type MigrationEntry = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -18,7 +19,7 @@ const migrations: MigrationEntry[] = [
|
|||||||
{ name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray },
|
{ name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray },
|
||||||
];
|
];
|
||||||
|
|
||||||
const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
const runMigrations = async (logger?: ILogger) => {
|
||||||
try {
|
try {
|
||||||
logger?.info({ message: "Running migrations", service: "Migrations" });
|
logger?.info({ message: "Running migrations", service: "Migrations" });
|
||||||
for (const migration of migrations) {
|
for (const migration of migrations) {
|
||||||
@@ -45,7 +46,7 @@ const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
|||||||
logger?.info({ message: "Migrations completed", service: "Migrations" });
|
logger?.info({ message: "Migrations completed", service: "Migrations" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const err = error as Error;
|
const err = error as Error;
|
||||||
logger?.error({ message: "Migration failed", service: "Migrations", details: err?.message, stack: err?.stack });
|
logger?.error({ message: "Migration failed", service: "Migrations", details: { error: err?.message }, stack: err?.stack });
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { IGeoChecksRepository } from "./IGeoChecksRepository.js";
|
import { IGeoChecksRepository } from "./IGeoChecksRepository.js";
|
||||||
import type { GeoCheck, GeoCheckMetadata, GeoCheckResult, GroupedGeoCheck, GeoContinent, FlatGeoCheck } from "@/types/geoCheck.js";
|
import type { GeoCheck, GeoCheckMetadata, GeoCheckResult, GroupedGeoCheck, GeoContinent, FlatGeoCheck } from "@/types/geoCheck.js";
|
||||||
import type { FlatGeoChecksQueryResult } from "./IGeoChecksRepository.js";
|
import type { FlatGeoChecksQueryResult } from "./IGeoChecksRepository.js";
|
||||||
import { GeoCheckModel, type GeoCheckDocument } from "@/db/models/index.js";
|
import { GeoCheckMetadataDocument, GeoCheckModel, type GeoCheckDocument } from "@/db/models/index.js";
|
||||||
import mongoose from "mongoose";
|
import mongoose, { PipelineStage } from "mongoose";
|
||||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||||
import { ILogger } from "@/utils/logger.js";
|
import { ILogger } from "@/utils/logger.js";
|
||||||
|
|
||||||
@@ -31,13 +31,13 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||||
};
|
};
|
||||||
|
|
||||||
const mapMetadata = (metadata: any): GeoCheckMetadata => ({
|
const mapMetadata = (metadata: GeoCheckMetadataDocument): GeoCheckMetadata => ({
|
||||||
monitorId: toStringId(metadata.monitorId),
|
monitorId: toStringId(metadata.monitorId),
|
||||||
teamId: toStringId(metadata.teamId),
|
teamId: toStringId(metadata.teamId),
|
||||||
type: metadata.type,
|
type: metadata.type,
|
||||||
});
|
});
|
||||||
|
|
||||||
const mapResults = (results: any[]): GeoCheckResult[] => {
|
const mapResults = (results: GeoCheckResult[]): GeoCheckResult[] => {
|
||||||
if (!results || !Array.isArray(results)) {
|
if (!results || !Array.isArray(results)) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -89,12 +89,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
return docs.map((doc) => this.toEntity(doc));
|
return docs.map((doc) => this.toEntity(doc));
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Failed to createGeoChecks: ${error.message}`,
|
message: error instanceof Error ? `Failed to createGeoChecks: ${error.message}` : "Failed to createGeoChecks",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "createGeoChecks",
|
method: "createGeoChecks",
|
||||||
stack: error.stack,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -109,7 +109,7 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
continents?: GeoContinent[]
|
continents?: GeoContinent[]
|
||||||
): Promise<FlatGeoChecksQueryResult> => {
|
): Promise<FlatGeoChecksQueryResult> => {
|
||||||
try {
|
try {
|
||||||
const matchStage: Record<string, any> = {
|
const matchStage: Record<string, unknown> = {
|
||||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||||
...(getDateForRange(dateRange) && {
|
...(getDateForRange(dateRange) && {
|
||||||
createdAt: {
|
createdAt: {
|
||||||
@@ -125,22 +125,8 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
skip = page * rowsPerPage;
|
skip = page * rowsPerPage;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (continents && continents.length > 0) {
|
|
||||||
const pipeline: any[] = [
|
|
||||||
{ $match: matchStage },
|
|
||||||
{ $unwind: "$results" },
|
|
||||||
{
|
|
||||||
$match: {
|
|
||||||
"results.location.continent": { $in: continents },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
} else {
|
|
||||||
const pipeline: any[] = [{ $match: matchStage }, { $unwind: "$results" }];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Common pipeline stages for both paths
|
// Common pipeline stages for both paths
|
||||||
const pipeline: any[] = [
|
const pipeline: PipelineStage[] = [
|
||||||
{ $match: matchStage },
|
{ $match: matchStage },
|
||||||
{ $unwind: "$results" },
|
{ $unwind: "$results" },
|
||||||
// Filter by continent if specified
|
// Filter by continent if specified
|
||||||
@@ -174,7 +160,7 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
];
|
];
|
||||||
|
|
||||||
// Count pipeline
|
// Count pipeline
|
||||||
const countPipeline: any[] = [
|
const countPipeline: PipelineStage[] = [
|
||||||
{ $match: matchStage },
|
{ $match: matchStage },
|
||||||
{ $unwind: "$results" },
|
{ $unwind: "$results" },
|
||||||
...(continents && continents.length > 0
|
...(continents && continents.length > 0
|
||||||
@@ -206,12 +192,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
return { geoChecksCount, geoChecks };
|
return { geoChecksCount, geoChecks };
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error finding geo checks by monitor ID: ${error.message}`,
|
message: error instanceof Error ? `Error finding geo checks by monitor ID: ${error.message}` : "Error finding geo checks by monitor ID",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "findByMonitorId",
|
method: "findByMonitorId",
|
||||||
stack: error.stack,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -227,11 +213,15 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
},
|
},
|
||||||
}).sort({ createdAt: -1 });
|
}).sort({ createdAt: -1 });
|
||||||
return docs.map(this.toEntity);
|
return docs.map(this.toEntity);
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error finding geo checks by monitor ID and date range: ${error.message}`,
|
message:
|
||||||
|
error instanceof Error
|
||||||
|
? `Error finding geo checks by monitor ID and date range: ${error.message}`
|
||||||
|
: "Error finding geo checks by monitor ID and date range",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "findByMonitorIdAndDateRange",
|
method: "findByMonitorIdAndDateRange",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -245,7 +235,7 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
continents?: GeoContinent[]
|
continents?: GeoContinent[]
|
||||||
): Promise<GroupedGeoCheck[]> => {
|
): Promise<GroupedGeoCheck[]> => {
|
||||||
try {
|
try {
|
||||||
const pipeline: any[] = [
|
const pipeline: PipelineStage[] = [
|
||||||
// Match geo checks for this monitor in date range
|
// Match geo checks for this monitor in date range
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
@@ -325,11 +315,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
|
|
||||||
const results = await GeoCheckModel.aggregate(pipeline);
|
const results = await GeoCheckModel.aggregate(pipeline);
|
||||||
return results as GroupedGeoCheck[];
|
return results as GroupedGeoCheck[];
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error finding grouped geo checks: ${error.message}`,
|
message: error instanceof Error ? `Error finding grouped geo checks: ${error.message}` : "Error finding grouped geo checks",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "findGroupedByMonitorIdAndDateRange",
|
method: "findGroupedByMonitorIdAndDateRange",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -341,11 +332,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||||
});
|
});
|
||||||
return result.deletedCount || 0;
|
return result.deletedCount || 0;
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error deleting geo checks by monitor ID: ${error.message}`,
|
message: error instanceof Error ? `Error deleting geo checks by monitor ID: ${error.message}` : "Error deleting geo checks by monitor ID",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "deleteByMonitorId",
|
method: "deleteByMonitorId",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -357,11 +349,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||||
});
|
});
|
||||||
return result.deletedCount || 0;
|
return result.deletedCount || 0;
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error deleting geo checks by team ID: ${error.message}`,
|
message: error instanceof Error ? `Error deleting geo checks by team ID: ${error.message}` : "Error deleting geo checks by team ID",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "deleteByTeamId",
|
method: "deleteByTeamId",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -372,11 +365,12 @@ class MongoGeoChecksRepository implements IGeoChecksRepository {
|
|||||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||||
const result = await GeoCheckModel.deleteMany({ "metadata.monitorId": { $nin: objectIds } });
|
const result = await GeoCheckModel.deleteMany({ "metadata.monitorId": { $nin: objectIds } });
|
||||||
return result.deletedCount || 0;
|
return result.deletedCount || 0;
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: `Error deleting orphaned geo checks: ${error.message}`,
|
message: error instanceof Error ? `Error deleting orphaned geo checks: ${error.message}` : "Error deleting orphaned geo checks",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "deleteByMonitorIdsNotIn",
|
method: "deleteByMonitorIdsNotIn",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ class MongoIncidentRepository implements IIncidentsRepository {
|
|||||||
status?: boolean;
|
status?: boolean;
|
||||||
monitorId?: string;
|
monitorId?: string;
|
||||||
resolutionType?: string;
|
resolutionType?: string;
|
||||||
}): Record<string, any> {
|
}): Record<string, unknown> {
|
||||||
const matchStage: Record<string, any> = {
|
const matchStage: Record<string, unknown> = {
|
||||||
teamId: new mongoose.Types.ObjectId(teamId),
|
teamId: new mongoose.Types.ObjectId(teamId),
|
||||||
...(status !== undefined && { status }),
|
...(status !== undefined && { status }),
|
||||||
...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }),
|
...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { MaintenanceWindow } from "@/types/index.js";
|
import type { MaintenanceWindow } from "@/types/index.js";
|
||||||
import { type MaintenanceWindowDocument, MaintenanceWindowModel } from "@/db/models/index.js";
|
import { type MaintenanceWindowDocument, MaintenanceWindowModel } from "@/db/models/index.js";
|
||||||
import { IMaintenanceWindowsRepository } from "./IMaintenanceWindowsRepository.js";
|
import { IMaintenanceWindowsRepository } from "./IMaintenanceWindowsRepository.js";
|
||||||
import mongoose from "mongoose";
|
import mongoose, { SortOrder } from "mongoose";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
|
||||||
class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository {
|
class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository {
|
||||||
@@ -81,7 +81,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
|
|||||||
order?: string,
|
order?: string,
|
||||||
active?: boolean
|
active?: boolean
|
||||||
): Promise<MaintenanceWindow[]> => {
|
): Promise<MaintenanceWindow[]> => {
|
||||||
const maintenanceQuery: Record<string, any> = { teamId };
|
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||||
|
|
||||||
if (active !== undefined) maintenanceQuery.active = active;
|
if (active !== undefined) maintenanceQuery.active = active;
|
||||||
|
|
||||||
@@ -92,7 +92,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sorting
|
// Sorting
|
||||||
const sort: Record<string, any> = {};
|
const sort: Record<string, SortOrder> = {};
|
||||||
if (field !== undefined && order !== undefined) {
|
if (field !== undefined && order !== undefined) {
|
||||||
sort[field] = order === "asc" ? 1 : -1;
|
sort[field] = order === "asc" ? 1 : -1;
|
||||||
}
|
}
|
||||||
@@ -127,7 +127,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
|
|||||||
return this.toEntity(deleted);
|
return this.toEntity(deleted);
|
||||||
};
|
};
|
||||||
countByTeamId = async (teamId: string, active?: boolean) => {
|
countByTeamId = async (teamId: string, active?: boolean) => {
|
||||||
const maintenanceQuery: Record<string, any> = { teamId };
|
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||||
|
|
||||||
if (active !== undefined) maintenanceQuery.active = active;
|
if (active !== undefined) maintenanceQuery.active = active;
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { MonitorModel } from "@/db/models/index.js";
|
import { MonitorModel } from "@/db/models/index.js";
|
||||||
import type { MonitorDocument, CheckSnapshotDocument } from "@/db/models/index.js";
|
import type { MonitorDocument, CheckSnapshotDocument } from "@/db/models/index.js";
|
||||||
import type { Monitor, MonitorsSummary, CheckSnapshot, Check } from "@/types/index.js";
|
import type { Monitor, MonitorsSummary, CheckSnapshot } from "@/types/index.js";
|
||||||
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
|
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
|
||||||
import type { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "./IMonitorsRepository.js";
|
import type { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "./IMonitorsRepository.js";
|
||||||
|
import { MongoBulkWriteError } from "mongodb";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
|
||||||
class MongoMonitorsRepository implements IMonitorsRepository {
|
class MongoMonitorsRepository implements IMonitorsRepository {
|
||||||
@@ -20,12 +21,9 @@ class MongoMonitorsRepository implements IMonitorsRepository {
|
|||||||
try {
|
try {
|
||||||
const inserted = await MonitorModel.insertMany(payload, { ordered: false });
|
const inserted = await MonitorModel.insertMany(payload, { ordered: false });
|
||||||
return this.mapDocuments(inserted);
|
return this.mapDocuments(inserted);
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
if (error.name === "MongoBulkWriteError" || error.name === "BulkWriteError") {
|
if (error instanceof MongoBulkWriteError && "insertedDocs" in error && Array.isArray(error.insertedDocs) && error.insertedDocs.length > 0) {
|
||||||
const insertedDocs = error.insertedDocs || [];
|
return this.mapDocuments(error.insertedDocs);
|
||||||
if (insertedDocs.length > 0) {
|
|
||||||
return this.mapDocuments(insertedDocs);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -46,7 +44,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
|
|||||||
};
|
};
|
||||||
|
|
||||||
findByTeamId = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null> => {
|
findByTeamId = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null> => {
|
||||||
const { page = 0, rowsPerPage = 0, filter, field = "createdAt", order = "desc", type, limit } = config ?? {};
|
const { page = 0, rowsPerPage = 0, filter, field = "createdAt", order = "desc", type } = config ?? {};
|
||||||
|
|
||||||
const query: Record<string, unknown> = {
|
const query: Record<string, unknown> = {
|
||||||
teamId: new mongoose.Types.ObjectId(teamId),
|
teamId: new mongoose.Types.ObjectId(teamId),
|
||||||
@@ -389,7 +387,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
|
|||||||
gameId: doc.gameId ?? undefined,
|
gameId: doc.gameId ?? undefined,
|
||||||
grpcServiceName: doc.grpcServiceName ?? undefined,
|
grpcServiceName: doc.grpcServiceName ?? undefined,
|
||||||
group: doc.group ?? null,
|
group: doc.group ?? null,
|
||||||
recentChecks: (doc.recentChecks ?? []).map((check: any) => this.toCheckSnapshot(check)),
|
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
|
||||||
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
||||||
geoCheckLocations: doc.geoCheckLocations ?? [],
|
geoCheckLocations: doc.geoCheckLocations ?? [],
|
||||||
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
||||||
@@ -398,7 +396,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
private toEntityWithChecks = (doc: any): Monitor => {
|
private toEntityWithChecks = (doc: MonitorDocument): Monitor => {
|
||||||
const toStringId = (value: unknown): string => {
|
const toStringId = (value: unknown): string => {
|
||||||
if (value instanceof mongoose.Types.ObjectId) {
|
if (value instanceof mongoose.Types.ObjectId) {
|
||||||
return value.toString();
|
return value.toString();
|
||||||
@@ -448,7 +446,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
|
|||||||
gameId: doc.gameId ?? undefined,
|
gameId: doc.gameId ?? undefined,
|
||||||
grpcServiceName: doc.grpcServiceName ?? undefined,
|
grpcServiceName: doc.grpcServiceName ?? undefined,
|
||||||
group: doc.group ?? null,
|
group: doc.group ?? null,
|
||||||
recentChecks: (doc.recentChecks ?? []).map((check: any) => this.toCheckSnapshot(check)),
|
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
|
||||||
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
||||||
geoCheckLocations: doc.geoCheckLocations ?? [],
|
geoCheckLocations: doc.geoCheckLocations ?? [],
|
||||||
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
||||||
|
|||||||
@@ -72,7 +72,8 @@ class MongoStatusPagesRepository implements IStatusPagesRepository {
|
|||||||
};
|
};
|
||||||
|
|
||||||
create = async (userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
|
create = async (userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
|
||||||
const { logo: _logo, ...restData } = data;
|
const { logo, ...restData } = data;
|
||||||
|
void logo;
|
||||||
const statusPage = new StatusPageModel({
|
const statusPage = new StatusPageModel({
|
||||||
...restData,
|
...restData,
|
||||||
userId,
|
userId,
|
||||||
@@ -110,7 +111,8 @@ class MongoStatusPagesRepository implements IStatusPagesRepository {
|
|||||||
image: Express.Multer.File | undefined,
|
image: Express.Multer.File | undefined,
|
||||||
patch: Partial<StatusPage> & { removeLogo?: string }
|
patch: Partial<StatusPage> & { removeLogo?: string }
|
||||||
): Promise<StatusPage> => {
|
): Promise<StatusPage> => {
|
||||||
const { logo: _logo, removeLogo, ...restPatch } = patch;
|
const { logo, removeLogo, ...restPatch } = patch;
|
||||||
|
void logo;
|
||||||
const updateData: StatusPageUpdateData = { ...restPatch };
|
const updateData: StatusPageUpdateData = { ...restPatch };
|
||||||
if (image) {
|
if (image) {
|
||||||
updateData.logo = {
|
updateData.logo = {
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ class MongoUsersRepository implements IUsersRepository {
|
|||||||
|
|
||||||
delete candidateUser.deleteProfileImage;
|
delete candidateUser.deleteProfileImage;
|
||||||
|
|
||||||
const updateQuery: Record<string, any> = { $set: candidateUser };
|
const updateQuery: Record<string, unknown> = { $set: candidateUser };
|
||||||
if (unsetFields) {
|
if (unsetFields) {
|
||||||
updateQuery.$unset = unsetFields;
|
updateQuery.$unset = unsetFields;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import { Router, RequestHandler } from "express";
|
import { Router, RequestHandler } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
import multer from "multer";
|
import multer from "multer";
|
||||||
|
import { IAuthController } from "@/controllers/authController.js";
|
||||||
|
|
||||||
const upload = multer();
|
const upload = multer();
|
||||||
|
|
||||||
class AuthRoutes {
|
class AuthRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private authController: any;
|
private authController: IAuthController;
|
||||||
|
|
||||||
constructor(authController: any, verifyJWT: RequestHandler) {
|
constructor(authController: IAuthController, verifyJWT: RequestHandler) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.authController = authController;
|
this.authController = authController;
|
||||||
this.initRoutes(verifyJWT);
|
this.initRoutes(verifyJWT);
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import { ICheckController } from "@/controllers/checkController.js";
|
||||||
|
|
||||||
class CheckRoutes {
|
class CheckRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private checkController: any;
|
private checkController: ICheckController;
|
||||||
|
|
||||||
constructor(checkController: any) {
|
constructor(checkController: ICheckController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.checkController = checkController;
|
this.checkController = checkController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { RequestHandler, Router } from "express";
|
import { RequestHandler, Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import { IDiagnosticController } from "@/controllers/diagnosticController.js";
|
||||||
|
|
||||||
class DiagnosticRoutes {
|
class DiagnosticRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private diagnosticController: any;
|
private diagnosticController: IDiagnosticController;
|
||||||
|
|
||||||
constructor(diagnosticController: any, verifyJWT: RequestHandler) {
|
constructor(diagnosticController: IDiagnosticController, verifyJWT: RequestHandler) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.diagnosticController = diagnosticController;
|
this.diagnosticController = diagnosticController;
|
||||||
this.initRoutes(verifyJWT);
|
this.initRoutes(verifyJWT);
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import { IGeoCheckController } from "@/controllers/geoCheckController.js";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
|
||||||
class GeoCheckRoutes {
|
class GeoCheckRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private geoCheckController: any;
|
private geoCheckController: IGeoCheckController;
|
||||||
|
|
||||||
constructor(geoCheckController: any) {
|
constructor(geoCheckController: IGeoCheckController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.geoCheckController = geoCheckController;
|
this.geoCheckController = geoCheckController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import { IIncidentController } from "@/controllers/incidentController.js";
|
||||||
|
|
||||||
class IncidentRoutes {
|
class IncidentRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private incidentController: any;
|
private incidentController: IIncidentController;
|
||||||
|
|
||||||
constructor(incidentController: any) {
|
constructor(incidentController: IIncidentController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.incidentController = incidentController;
|
this.incidentController = incidentController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { RequestHandler, Router } from "express";
|
import { RequestHandler, Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import { IInviteController } from "@/controllers/inviteController.js";
|
||||||
|
|
||||||
class InviteRoutes {
|
class InviteRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private inviteController: any;
|
private inviteController: IInviteController;
|
||||||
|
|
||||||
constructor(inviteController: any, verifyJWT: RequestHandler) {
|
constructor(inviteController: IInviteController, verifyJWT: RequestHandler) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.inviteController = inviteController;
|
this.inviteController = inviteController;
|
||||||
this.initRoutes(verifyJWT);
|
this.initRoutes(verifyJWT);
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "@/middleware/isAllowed.js";
|
||||||
|
import { ILogController } from "@/controllers/logController.js";
|
||||||
class LogRoutes {
|
class LogRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private logController: any;
|
private logController: ILogController;
|
||||||
|
|
||||||
constructor(logController: any) {
|
constructor(logController: ILogController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.logController = logController;
|
this.logController = logController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import { IMaintenanceWindowController } from "@/controllers/maintenanceWindowController.js";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
|
||||||
class MaintenanceWindowRoutes {
|
class MaintenanceWindowRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private mwController: any;
|
private mwController: IMaintenanceWindowController;
|
||||||
|
|
||||||
constructor(maintenanceWindowController: any) {
|
constructor(maintenanceWindowController: IMaintenanceWindowController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.mwController = maintenanceWindowController;
|
this.mwController = maintenanceWindowController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "@/middleware/isAllowed.js";
|
import { isAllowed } from "@/middleware/isAllowed.js";
|
||||||
import multer from "multer";
|
import { IMonitorController } from "@/controllers/monitorController.js";
|
||||||
import { fetchMonitorCertificate } from "@/controllers/controllerUtils.js";
|
|
||||||
const upload = multer({
|
|
||||||
storage: multer.memoryStorage(), // Store file in memory as Buffer
|
|
||||||
});
|
|
||||||
|
|
||||||
class MonitorRoutes {
|
class MonitorRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private monitorController: any;
|
private monitorController: IMonitorController;
|
||||||
constructor(monitorController: any) {
|
constructor(monitorController: IMonitorController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.monitorController = monitorController;
|
this.monitorController = monitorController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
@@ -38,7 +34,7 @@ class MonitorRoutes {
|
|||||||
|
|
||||||
// Util routes
|
// Util routes
|
||||||
this.router.get("/certificate/:monitorId", (req, res, next) => {
|
this.router.get("/certificate/:monitorId", (req, res, next) => {
|
||||||
this.monitorController.getMonitorCertificate(req, res, next, fetchMonitorCertificate);
|
this.monitorController.getMonitorCertificate(req, res, next);
|
||||||
});
|
});
|
||||||
|
|
||||||
// General monitor CRUD routes
|
// General monitor CRUD routes
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
|
import { INotificationController } from "@/controllers/notificationController.js";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
class NotificationRoutes {
|
class NotificationRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private notificationController: any;
|
private notificationController: INotificationController;
|
||||||
|
|
||||||
constructor(notificationController: any) {
|
constructor(notificationController: INotificationController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.notificationController = notificationController;
|
this.notificationController = notificationController;
|
||||||
this.initializeRoutes();
|
this.initializeRoutes();
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "@/middleware/isAllowed.js";
|
||||||
|
import { IJobQueueController } from "@/controllers/queueController.js";
|
||||||
class QueueRoutes {
|
class QueueRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private queueController: any;
|
private queueController: IJobQueueController;
|
||||||
|
|
||||||
constructor(queueController: any) {
|
constructor(queueController: IJobQueueController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.queueController = queueController;
|
this.queueController = queueController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import { ISettingsController } from "@/controllers/settingsController.js";
|
||||||
|
|
||||||
class SettingsRoutes {
|
class SettingsRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private settingsController: any;
|
private settingsController: ISettingsController;
|
||||||
|
|
||||||
constructor(settingsController: any) {
|
constructor(settingsController: ISettingsController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.settingsController = settingsController;
|
this.settingsController = settingsController;
|
||||||
this.initRoutes();
|
this.initRoutes();
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
|
import { IStatusPageController } from "@/controllers/statusPageController.js";
|
||||||
import { RequestHandler, Router } from "express";
|
import { RequestHandler, Router } from "express";
|
||||||
import multer from "multer";
|
import multer from "multer";
|
||||||
const upload = multer();
|
const upload = multer();
|
||||||
|
|
||||||
class StatusPageRoutes {
|
class StatusPageRoutes {
|
||||||
private router: Router;
|
private router: Router;
|
||||||
private statusPageController: any;
|
private statusPageController: IStatusPageController;
|
||||||
|
|
||||||
constructor(statusPageController: any, verifyJWT: RequestHandler, verifyStatusPageAccess: RequestHandler) {
|
constructor(statusPageController: IStatusPageController, verifyJWT: RequestHandler, verifyStatusPageAccess: RequestHandler) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
this.statusPageController = statusPageController;
|
this.statusPageController = statusPageController;
|
||||||
this.initRoutes(verifyJWT, verifyStatusPageAccess);
|
this.initRoutes(verifyJWT, verifyStatusPageAccess);
|
||||||
|
|||||||
@@ -24,8 +24,7 @@ export class DiagnosticService implements IDiagnosticService {
|
|||||||
* Clears performance marks after each measurement to prevent memory leaks.
|
* Clears performance marks after each measurement to prevent memory leaks.
|
||||||
*/
|
*/
|
||||||
const obs = new PerformanceObserver((items) => {
|
const obs = new PerformanceObserver((items) => {
|
||||||
// Get the first entry but we don't need to store it
|
items.getEntries();
|
||||||
items.getEntries()[0];
|
|
||||||
performance.clearMarks();
|
performance.clearMarks();
|
||||||
});
|
});
|
||||||
obs.observe({ entryTypes: ["measure"] });
|
obs.observe({ entryTypes: ["measure"] });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Monitor, GeoCheck } from "@/types/index.js";
|
import type { Monitor, GeoCheck } from "@/types/index.js";
|
||||||
import type { GeoCheckResult } from "@/types/geoCheck.js";
|
import type { GeoCheckResult, GeoContinent } from "@/types/geoCheck.js";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import type { IGeoChecksRepository } from "@/repositories/index.js";
|
import type { FlatGeoChecksQueryResult, IGeoChecksRepository } from "@/repositories/index.js";
|
||||||
import type { IMonitorsRepository } from "@/repositories/index.js";
|
import type { IMonitorsRepository } from "@/repositories/index.js";
|
||||||
import type { IGlobalPingService } from "@/service/infrastructure/globalPingService.js";
|
import type { IGlobalPingService } from "@/service/infrastructure/globalPingService.js";
|
||||||
import type { ILogger } from "@/utils/logger.js";
|
import type { ILogger } from "@/utils/logger.js";
|
||||||
@@ -13,7 +13,15 @@ export interface IGeoChecksService {
|
|||||||
readonly serviceName: string;
|
readonly serviceName: string;
|
||||||
buildGeoCheck(monitor: Monitor): Promise<GeoCheck | null>;
|
buildGeoCheck(monitor: Monitor): Promise<GeoCheck | null>;
|
||||||
createGeoChecks(geoChecks: GeoCheck[]): Promise<GeoCheck[]>;
|
createGeoChecks(geoChecks: GeoCheck[]): Promise<GeoCheck[]>;
|
||||||
getGeoChecksByMonitor(args: { monitorId: string; query: any; teamId: string }): Promise<any>;
|
getGeoChecksByMonitor(args: {
|
||||||
|
monitorId: string;
|
||||||
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
|
dateRange: string;
|
||||||
|
page?: number;
|
||||||
|
rowsPerPage?: number;
|
||||||
|
continent: GeoContinent | GeoContinent[];
|
||||||
|
}): Promise<FlatGeoChecksQueryResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class GeoChecksService implements IGeoChecksService {
|
export class GeoChecksService implements IGeoChecksService {
|
||||||
@@ -139,7 +147,23 @@ export class GeoChecksService implements IGeoChecksService {
|
|||||||
return this.geoChecksRepository.createGeoChecks(geoChecks);
|
return this.geoChecksRepository.createGeoChecks(geoChecks);
|
||||||
};
|
};
|
||||||
|
|
||||||
getGeoChecksByMonitor = async ({ monitorId, query, teamId }: { monitorId: string; query: any; teamId: string }) => {
|
getGeoChecksByMonitor = async ({
|
||||||
|
monitorId,
|
||||||
|
teamId,
|
||||||
|
sortOrder,
|
||||||
|
dateRange,
|
||||||
|
page,
|
||||||
|
rowsPerPage,
|
||||||
|
continent,
|
||||||
|
}: {
|
||||||
|
monitorId: string;
|
||||||
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
|
dateRange: string;
|
||||||
|
page?: number;
|
||||||
|
rowsPerPage?: number;
|
||||||
|
continent: GeoContinent | GeoContinent[];
|
||||||
|
}) => {
|
||||||
if (!monitorId) {
|
if (!monitorId) {
|
||||||
throw new AppError({
|
throw new AppError({
|
||||||
message: "No monitor ID in request",
|
message: "No monitor ID in request",
|
||||||
@@ -167,10 +191,9 @@ export class GeoChecksService implements IGeoChecksService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const { sortOrder, dateRange, page, rowsPerPage, continent } = query;
|
|
||||||
const continents = continent ? (Array.isArray(continent) ? continent : [continent]) : undefined;
|
const continents = continent ? (Array.isArray(continent) ? continent : [continent]) : undefined;
|
||||||
const parsedPage = page ? parseInt(page) : page;
|
const parsedPage = page || 0;
|
||||||
const parsedRowsPerPage = rowsPerPage ? parseInt(rowsPerPage) : rowsPerPage;
|
const parsedRowsPerPage = rowsPerPage || 5;
|
||||||
const result = await this.geoChecksRepository.findByMonitorId(monitorId, sortOrder, dateRange, parsedPage, parsedRowsPerPage, continents);
|
const result = await this.geoChecksRepository.findByMonitorId(monitorId, sortOrder, dateRange, parsedPage, parsedRowsPerPage, continents);
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import type { Invite, UserRole } from "@/types/index.js";
|
|||||||
import { canManageRole } from "@/types/user.js";
|
import { canManageRole } from "@/types/user.js";
|
||||||
import type { IInvitesRepository } from "@/repositories/index.js";
|
import type { IInvitesRepository } from "@/repositories/index.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
import { ISettingsService } from "../system/settingsService.js";
|
||||||
|
import { IEmailService } from "../infrastructure/emailService.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "inviteService";
|
const SERVICE_NAME = "inviteService";
|
||||||
|
|
||||||
@@ -14,8 +16,8 @@ export interface IInviteService {
|
|||||||
export class InviteService implements IInviteService {
|
export class InviteService implements IInviteService {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private settingsService: any;
|
private settingsService: ISettingsService;
|
||||||
private emailService: any;
|
private emailService: IEmailService;
|
||||||
private invitesRepository: IInvitesRepository;
|
private invitesRepository: IInvitesRepository;
|
||||||
|
|
||||||
constructor({
|
constructor({
|
||||||
@@ -24,8 +26,8 @@ export class InviteService implements IInviteService {
|
|||||||
emailService,
|
emailService,
|
||||||
}: {
|
}: {
|
||||||
invitesRepository: IInvitesRepository;
|
invitesRepository: IInvitesRepository;
|
||||||
settingsService: any;
|
settingsService: ISettingsService;
|
||||||
emailService: any;
|
emailService: IEmailService;
|
||||||
}) {
|
}) {
|
||||||
this.invitesRepository = invitesRepository;
|
this.invitesRepository = invitesRepository;
|
||||||
this.settingsService = settingsService;
|
this.settingsService = settingsService;
|
||||||
@@ -57,8 +59,16 @@ export class InviteService implements IInviteService {
|
|||||||
return inviteToken;
|
return inviteToken;
|
||||||
};
|
};
|
||||||
|
|
||||||
sendInviteEmail = async ({ invite, firstName, userRoles }: { invite: Partial<Invite>; firstName: any; userRoles: UserRole[] }) => {
|
sendInviteEmail = async ({ invite, firstName, userRoles }: { invite: Partial<Invite>; firstName: string; userRoles: UserRole[] }) => {
|
||||||
const inviteRoles = invite.role ?? [];
|
const inviteRoles = invite.role ?? [];
|
||||||
|
if (!invite.email) {
|
||||||
|
throw new AppError({
|
||||||
|
message: "Invite email is required to send an invite",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "sendInviteEmail",
|
||||||
|
status: 400,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for (const targetRole of inviteRoles) {
|
for (const targetRole of inviteRoles) {
|
||||||
const canManage = userRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
const canManage = userRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
||||||
@@ -66,7 +76,7 @@ export class InviteService implements IInviteService {
|
|||||||
throw new AppError({
|
throw new AppError({
|
||||||
message: "You do not have permission to create this invite",
|
message: "You do not have permission to create this invite",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getInviteToken",
|
method: "sendInviteEmail",
|
||||||
status: 403,
|
status: 403,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -79,6 +89,16 @@ export class InviteService implements IInviteService {
|
|||||||
name: firstName,
|
name: firstName,
|
||||||
link: `${clientHost}/register/${inviteToken.token}`,
|
link: `${clientHost}/register/${inviteToken.token}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!html) {
|
||||||
|
throw new AppError({
|
||||||
|
message: "Failed to build invite e-mail... Please verify your settings.",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "sendInviteEmail",
|
||||||
|
status: 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const result = await this.emailService.sendEmail(invite.email, "Welcome to Uptime Monitor", html);
|
const result = await this.emailService.sendEmail(invite.email, "Welcome to Uptime Monitor", html);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
throw new AppError({
|
throw new AppError({
|
||||||
|
|||||||
@@ -1,11 +1,21 @@
|
|||||||
import { IMaintenanceWindowsRepository, IMonitorsRepository } from "@/repositories/index.js";
|
import { IMaintenanceWindowsRepository, IMonitorsRepository } from "@/repositories/index.js";
|
||||||
import type { MaintenanceWindow } from "@/types/index.js";
|
import type { DurationUnit, MaintenanceWindow } from "@/types/index.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "maintenanceWindowService";
|
const SERVICE_NAME = "maintenanceWindowService";
|
||||||
|
|
||||||
export interface IMaintenanceWindowService {
|
export interface IMaintenanceWindowService {
|
||||||
createMaintenanceWindow(params: { teamId: string; body: Partial<MaintenanceWindow> & { monitors: string[] } }): Promise<void>;
|
createMaintenanceWindow(params: {
|
||||||
|
teamId: string;
|
||||||
|
monitorIDs: string[];
|
||||||
|
name: string;
|
||||||
|
active: boolean;
|
||||||
|
duration: number;
|
||||||
|
durationUnit: DurationUnit;
|
||||||
|
repeat: number;
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
}): Promise<void>;
|
||||||
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||||
getMaintenanceWindowsByTeamId(params: {
|
getMaintenanceWindowsByTeamId(params: {
|
||||||
teamId: string;
|
teamId: string;
|
||||||
@@ -40,9 +50,28 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
|
|||||||
return MaintenanceWindowService.SERVICE_NAME;
|
return MaintenanceWindowService.SERVICE_NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
createMaintenanceWindow = async ({ teamId, body }: { teamId: string; body: any }) => {
|
createMaintenanceWindow = async ({
|
||||||
const monitorIds = body.monitors;
|
teamId,
|
||||||
const monitors = await this.monitorsRepository.findByIds(monitorIds);
|
monitorIDs,
|
||||||
|
name,
|
||||||
|
active,
|
||||||
|
duration,
|
||||||
|
durationUnit,
|
||||||
|
repeat,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
}: {
|
||||||
|
teamId: string;
|
||||||
|
monitorIDs: string[];
|
||||||
|
name: string;
|
||||||
|
active: boolean;
|
||||||
|
duration: number;
|
||||||
|
durationUnit: DurationUnit;
|
||||||
|
repeat: number;
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
}) => {
|
||||||
|
const monitors = await this.monitorsRepository.findByIds(monitorIDs);
|
||||||
|
|
||||||
const unauthorizedMonitors = monitors.filter((monitor) => monitor.teamId !== teamId);
|
const unauthorizedMonitors = monitors.filter((monitor) => monitor.teamId !== teamId);
|
||||||
|
|
||||||
@@ -55,17 +84,17 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const dbTransactions = monitorIds.map((monitorId: string) => {
|
const dbTransactions = monitorIDs.map((monitorId: string) => {
|
||||||
return this.maintenanceWindowsRepository.create({
|
return this.maintenanceWindowsRepository.create({
|
||||||
teamId,
|
teamId,
|
||||||
monitorId,
|
monitorId,
|
||||||
name: body.name,
|
name: name,
|
||||||
active: body.active ? body.active : true,
|
active: active,
|
||||||
duration: body.duration,
|
duration: duration,
|
||||||
durationUnit: body.durationUnit,
|
durationUnit: durationUnit,
|
||||||
repeat: body.repeat,
|
repeat: repeat,
|
||||||
start: body.start,
|
start: start,
|
||||||
end: body.end,
|
end: end,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
await Promise.all(dbTransactions);
|
await Promise.all(dbTransactions);
|
||||||
@@ -106,7 +135,7 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
|
|||||||
return await this.maintenanceWindowsRepository.deleteById(id, teamId);
|
return await this.maintenanceWindowsRepository.deleteById(id, teamId);
|
||||||
};
|
};
|
||||||
|
|
||||||
editMaintenanceWindow = async ({ id, teamId, body }: { id: string; teamId: string; body: any }) => {
|
editMaintenanceWindow = async ({ id, teamId, body }: { id: string; teamId: string; body: Partial<MaintenanceWindow> }) => {
|
||||||
return await this.maintenanceWindowsRepository.updateById(id, teamId, body);
|
return await this.maintenanceWindowsRepository.updateById(id, teamId, body);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,11 @@ import { Monitor } from "@/types/monitor.js";
|
|||||||
import jmespath from "jmespath";
|
import jmespath from "jmespath";
|
||||||
type JmesPath = typeof jmespath;
|
type JmesPath = typeof jmespath;
|
||||||
|
|
||||||
export class AdvancedMatcher {
|
export interface IAdvancedMatcher {
|
||||||
|
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AdvancedMatcher implements IAdvancedMatcher {
|
||||||
constructor(private jmespath: JmesPath) {}
|
constructor(private jmespath: JmesPath) {}
|
||||||
|
|
||||||
private compare(actual: unknown, expected: string, method?: string): boolean {
|
private compare(actual: unknown, expected: string, method?: string): boolean {
|
||||||
@@ -12,7 +16,7 @@ export class AdvancedMatcher {
|
|||||||
return String(actual) === expected; // Default
|
return String(actual) === expected; // Default
|
||||||
}
|
}
|
||||||
|
|
||||||
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: any } {
|
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined } {
|
||||||
const { useAdvancedMatching, jsonPath, matchMethod, expectedValue } = monitor;
|
const { useAdvancedMatching, jsonPath, matchMethod, expectedValue } = monitor;
|
||||||
if (!useAdvancedMatching) return { ok: true, message: "Success" };
|
if (!useAdvancedMatching) return { ok: true, message: "Success" };
|
||||||
|
|
||||||
@@ -35,10 +39,10 @@ export class AdvancedMatcher {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const isFalsey = dataToValidate === false || dataToValidate === "false" || dataToValidate === undefined || dataToValidate === null;
|
const isFalsy = dataToValidate === false || dataToValidate === "false" || dataToValidate === undefined || dataToValidate === null;
|
||||||
return {
|
return {
|
||||||
ok: !isFalsey,
|
ok: !isFalsy,
|
||||||
message: !isFalsey ? "Success" : "Extracted value is falsey",
|
message: !isFalsy ? "Success" : "Extracted value is falsy",
|
||||||
extracted: dataToValidate,
|
extracted: dataToValidate,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { type Got, HTTPError, RequestError } from "got";
|
import { type Got, HTTPError, RequestError } from "got";
|
||||||
import { AdvancedMatcher } from "@/service/infrastructure/network/AdvancedMatcher.js";
|
import { IAdvancedMatcher } from "@/service/infrastructure/network/AdvancedMatcher.js";
|
||||||
import { IStatusProvider } from "@/service/infrastructure/network/IStatusProvider.js";
|
import { IStatusProvider } from "@/service/infrastructure/network/IStatusProvider.js";
|
||||||
import { HttpStatusPayload } from "@/types/network.js";
|
import { HttpStatusPayload } from "@/types/network.js";
|
||||||
import { MonitorStatusResponse } from "@/types/network.js";
|
import { MonitorStatusResponse } from "@/types/network.js";
|
||||||
@@ -13,7 +13,7 @@ export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private got: Got,
|
private got: Got,
|
||||||
private advancedMatcher: AdvancedMatcher
|
private advancedMatcher: IAdvancedMatcher
|
||||||
) {
|
) {
|
||||||
const cacheable = new CacheableLookup({ maxTtl: 300, errorTtl: 30 });
|
const cacheable = new CacheableLookup({ maxTtl: 300, errorTtl: 30 });
|
||||||
this.got = got.extend({
|
this.got = got.extend({
|
||||||
|
|||||||
Reference in new issue
Block a user