refactor server

This commit is contained in:
Alex Holliday committed 2025-07-25 15:15:14 -07:00
1 parent 6cb538ce69
commit acc910cbc0
48 files changed
+584 -650

No files matched your search

+4
View File
@@ -10,6 +10,10 @@ class CheckService {
this.errorService = errorService;
}
get serviceName() {
return CheckService.SERVICE_NAME;
}
getChecksByMonitor = async ({ monitorId, query, teamId }) => {
if (!monitorId) {
throw this.errorService.createBadRequestError("No monitor ID in request");
@@ -5,6 +5,7 @@ const SERVICE_NAME = "diagnosticService";
class DiagnosticService {
static SERVICE_NAME = SERVICE_NAME;
constructor() {
/**
* Performance Observer for monitoring system performance metrics.
@@ -18,6 +19,10 @@ class DiagnosticService {
obs.observe({ entryTypes: ["measure"] });
}
get serviceName() {
return DiagnosticService.SERVICE_NAME;
}
getCPUUsage = async () => {
const startUsage = process.cpuUsage();
const timingPeriod = 1000; // measured in ms
+4
View File
@@ -11,6 +11,10 @@ class InviteService {
this.errorService = errorService;
}
get serviceName() {
return InviteService.SERVICE_NAME;
}
getInviteToken = async ({ invite, teamId }) => {
invite.teamId = teamId;
const inviteToken = await this.db.requestInviteToken(invite);
@@ -2,6 +2,7 @@ const SERVICE_NAME = "maintenanceWindowService";
class MaintenanceWindowService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, stringService, errorService }) {
this.db = db;
this.settingsService = settingsService;
@@ -9,6 +10,10 @@ class MaintenanceWindowService {
this.errorService = errorService;
}
get serviceName() {
return MaintenanceWindowService.SERVICE_NAME;
}
createMaintenanceWindow = async ({ teamId, body }) => {
const monitorIds = body.monitors;
const monitors = await this.db.getMonitorsByIds(monitorIds);
+5 -1
View File
@@ -2,7 +2,7 @@ import { createMonitorsBodyValidation } from "../../validation/joi.js";
const SERVICE_NAME = "MonitorService";
class MonitorService {
SERVICE_NAME = SERVICE_NAME;
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, jobQueue, stringService, emailService, papaparse, logger, errorService }) {
this.db = db;
@@ -15,6 +15,10 @@ class MonitorService {
this.errorService = errorService;
}
get serviceName() {
return MonitorService.SERVICE_NAME;
}
verifyTeamAccess = async ({ teamId, monitorId }) => {
const monitor = await this.db.getMonitorById(monitorId);
if (!monitor?.teamId?.equals(teamId)) {
+5
View File
@@ -2,6 +2,7 @@ const SERVICE_NAME = "userService";
class UserService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, emailService, settingsService, logger, stringService, jwt, errorService }) {
this.db = db;
this.emailService = emailService;
@@ -12,6 +13,10 @@ class UserService {
this.errorService = errorService;
}
get serviceName() {
return UserService.SERVICE_NAME;
}
issueToken = (payload, appSettings) => {
const tokenTTL = appSettings?.jwtTTL ?? "2h";
const tokenSecret = appSettings?.jwtSecret;
+5
View File
@@ -2,12 +2,17 @@ const SERVICE_NAME = "RedisService";
class RedisService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ Redis, logger }) {
this.Redis = Redis;
this.connections = new Set();
this.logger = logger;
}
get serviceName() {
return RedisService.SERVICE_NAME;
}
getNewConnection(options = {}) {
const connection = new this.Redis(process.env.REDIS_URL, {
retryStrategy: (times) => {
@@ -23,6 +23,10 @@ class JobQueue {
this.workers = [];
}
get serviceName() {
return JobQueue.SERVICE_NAME;
}
static async create({ db, jobQueueHelper, logger, stringService }) {
const instance = new JobQueue({ db, jobQueueHelper, logger, stringService });
await instance.init();
@@ -1,6 +1,8 @@
const SERVICE_NAME = "JobQueueHelper";
class JobQueueHelper {
static SERVICE_NAME = SERVICE_NAME;
constructor({ redisService, Queue, Worker, logger, db, networkService, statusService, notificationService }) {
this.db = db;
this.redisService = redisService;
@@ -12,6 +14,10 @@ class JobQueueHelper {
this.notificationService = notificationService;
}
get serviceName() {
return JobQueueHelper.SERVICE_NAME;
}
createQueue(queueName) {
const connection = this.redisService.getNewConnection();
const q = new this.Queue(queueName, {
@@ -1,6 +1,6 @@
import { Pulse } from "@pulsecron/pulse";
const SERVICE_NAME = "PulseQueue";
const SERVICE_NAME = "JobQueue";
class PulseQueue {
static SERVICE_NAME = SERVICE_NAME;
@@ -11,6 +11,10 @@ class PulseQueue {
this.logger = logger;
}
get serviceName() {
return PulseQueue.SERVICE_NAME;
}
static async create({ appSettings, db, pulseQueueHelper, logger }) {
const instance = new PulseQueue({ appSettings, db, pulseQueueHelper, logger });
await instance.init();
@@ -1,6 +1,8 @@
const SERVICE_NAME = "PulseQueueHelper";
class PulseQueueHelper {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, logger, networkService, statusService, notificationService }) {
this.db = db;
this.logger = logger;
@@ -9,6 +11,10 @@ class PulseQueueHelper {
this.notificationService = notificationService;
}
get serviceName() {
return PulseQueueHelper.SERVICE_NAME;
}
getMonitorJob = () => {
return async (job) => {
try {
@@ -1,5 +1,5 @@
import Scheduler from "super-simple-scheduler";
const SERVICE_NAME = "SuperSimpleQueue";
const SERVICE_NAME = "JobQueue";
class SuperSimpleQueue {
static SERVICE_NAME = SERVICE_NAME;
@@ -11,6 +11,10 @@ class SuperSimpleQueue {
this.helper = helper;
}
get serviceName() {
return SuperSimpleQueue.SERVICE_NAME;
}
static async create({ appSettings, db, logger, helper }) {
const instance = new SuperSimpleQueue({ appSettings, db, logger, helper });
await instance.init();
@@ -1,6 +1,7 @@
const SERVICE_NAME = "SuperSimpleQueueHelper";
const SERVICE_NAME = "JobQueueHelper";
class SuperSimpleQueueHelper {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, logger, networkService, statusService, notificationService }) {
this.db = db;
this.logger = logger;
@@ -9,6 +10,10 @@ class SuperSimpleQueueHelper {
this.notificationService = notificationService;
}
get serviceName() {
return SuperSimpleQueueHelper.SERVICE_NAME;
}
getMonitorJob = () => {
return async (monitor) => {
try {
@@ -10,6 +10,7 @@ const TYPE_MAP = {
};
class BufferService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, logger }) {
this.db = db;
this.logger = logger;
@@ -32,7 +33,10 @@ class BufferService {
method: "constructor",
});
}
static SERVICE_NAME = SERVICE_NAME;
get serviceName() {
return BufferService.SERVICE_NAME;
}
addToBuffer({ check, type }) {
try {
@@ -33,6 +33,10 @@ class EmailService {
this.init();
}
get serviceName() {
return EmailService.SERVICE_NAME;
}
init = async () => {
/**
* Loads an email template from the filesystem.
@@ -42,7 +46,7 @@ class EmailService {
*/
this.loadTemplate = (templateName) => {
try {
const templatePath = this.path.join(__dirname, `../templates/${templateName}.mjml`);
const templatePath = this.path.join(__dirname, `../../templates/${templateName}.mjml`);
const templateContent = this.fs.readFileSync(templatePath, "utf8");
return this.compile(templateContent);
} catch (error) {
@@ -55,9 +55,12 @@ class BadRequestError extends AppError {
const SERVICE_NAME = "ErrorService";
class ErrorService {
static SERVICE_NAME = SERVICE_NAME;
constructor() {}
get serviceName() {
return ErrorService.SERVICE_NAME;
}
createError = (message, status = 500, service = null, method = null, details = null) => {
return new AppError(message, status, service, method, details);
};
@@ -36,6 +36,10 @@ class NetworkService {
this.settingsService = settingsService;
}
get serviceName() {
return NetworkService.SERVICE_NAME;
}
/**
* Times the execution of an asynchronous operation.
*
@@ -12,6 +12,10 @@ class NotificationService {
this.notificationUtils = notificationUtils;
}
get serviceName() {
return NotificationService.SERVICE_NAME;
}
sendNotification = async ({ notification, subject, content, html }) => {
const { type, address } = notification;
@@ -1,9 +1,17 @@
const SERVICE_NAME = "NotificationUtils";
class NotificationUtils {
static SERVICE_NAME = SERVICE_NAME;
constructor({ stringService, emailService }) {
this.stringService = stringService;
this.emailService = emailService;
}
get serviceName() {
return NotificationUtils.SERVICE_NAME;
}
buildTestEmail = async () => {
const context = { testName: "Monitoring System" };
const html = await this.emailService.buildEmail("testEmailTemplate", context);
@@ -4,6 +4,7 @@ const SERVICE_NAME = "StatusService";
class StatusService {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates an instance of StatusService.
*
@@ -14,7 +15,10 @@ class StatusService {
this.db = db;
this.logger = logger;
this.buffer = buffer;
this.SERVICE_NAME = SERVICE_NAME;
}
get serviceName() {
return StatusService.SERVICE_NAME;
}
async updateRunningStats({ monitor, networkResponse }) {
+4
View File
@@ -6,6 +6,10 @@ class ServiceRegistry {
this.services = {};
}
get serviceName() {
return ServiceRegistry.SERVICE_NAME;
}
register(name, service) {
logger.info({
message: `Registering service ${name}`,
+8 -1
View File
@@ -1,4 +1,5 @@
const SERVICE_NAME = "SettingsService";
const envConfig = {
nodeEnv: process.env.NODE_ENV,
logLevel: process.env.LOG_LEVEL,
@@ -23,7 +24,8 @@ const envConfig = {
* This service is responsible for loading and managing the application settings.
*/
class SettingsService {
static SERVICE_NAME = SERVICE_NAME;
static SERVICE_NAME = "SettingsService";
/**
* Constructs a new SettingsService
* @constructor
@@ -32,6 +34,11 @@ class SettingsService {
this.AppSettings = AppSettings;
this.settings = { ...envConfig };
}
get serviceName() {
return SettingsService.SERVICE_NAME;
}
/**
* Load settings from env settings
* @returns {Object>} The settings.
+7 -1
View File
@@ -1,5 +1,7 @@
const SERVICE_NAME = "StringService";
class StringService {
static SERVICE_NAME = "StringService";
static SERVICE_NAME = SERVICE_NAME;
constructor(translationService) {
if (StringService.instance) {
@@ -11,6 +13,10 @@ class StringService {
StringService.instance = this;
}
get serviceName() {
return StringService.SERVICE_NAME;
}
setLanguage(language) {
this._language = language;
}
+4 -1
View File
@@ -3,7 +3,6 @@ import path from "path";
class TranslationService {
static SERVICE_NAME = "TranslationService";
constructor(logger) {
this.logger = logger;
this.translations = {};
@@ -11,6 +10,10 @@ class TranslationService {
this.localesDir = path.join(process.cwd(), "locales");
}
get serviceName() {
return TranslationService.SERVICE_NAME;
}
setLanguage(language) {
this._language = language;
}
-208
View File
@@ -1,208 +0,0 @@
const SERVICE_NAME = "userService";
import { createAuthError, createError } from "../utils/errorUtils.js";
class UserService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, emailService, settingsService, logger, stringService, jwt }) {
this.db = db;
this.emailService = emailService;
this.settingsService = settingsService;
this.logger = logger;
this.stringService = stringService;
this.jwt = jwt;
}
issueToken = (payload, appSettings) => {
const tokenTTL = appSettings?.jwtTTL ?? "2h";
const tokenSecret = appSettings?.jwtSecret;
const payloadData = payload;
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
};
registerUser = async (user, file) => {
// Create a new user
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await this.db.checkSuperadmin();
if (superAdminExists) {
const invitedUser = await this.db.getInviteTokenAndDelete(user.inviteToken);
user.role = invitedUser.role;
user.teamId = invitedUser.teamId;
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex");
await this.db.updateAppSettings({ jwtSecret });
}
const newUser = await this.db.insertUser({ ...user }, file);
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
details: newUser._id,
});
const userForToken = { ...newUser._doc };
delete userForToken.profileImage;
delete userForToken.avatarImage;
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userForToken, appSettings);
try {
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
name: newUser.firstName,
});
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error) => {
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
});
} catch (error) {
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}
return { user: newUser, token };
};
loginUser = async (email, password) => {
// Check if user exists
const user = await this.db.getUserByEmail(email);
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
throw createAuthError(this.stringService.authIncorrectPassword);
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return { user: userWithoutPassword, token };
};
editUser = async (updates, file, currentUser) => {
// Change Password check
if (updates?.password && updates?.newPassword) {
// Get user's email
// Add user email to body for DB operation
updates.email = currentUser.email;
// Get user
const user = await this.db.getUserByEmail(currentUser.email);
// Compare passwords
const match = await user.comparePassword(updates?.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
throw createError(this.stringService.authIncorrectPassword, 403);
}
// If a match, update the password
updates.password = updates.newPassword;
}
const updatedUser = await this.db.updateUser({ userId: currentUser?._id, user: updates, file: file });
return updatedUser;
};
checkSuperadminExists = async () => {
const superAdminExists = await this.db.checkSuperadmin();
return superAdminExists;
};
requestRecovery = async (email) => {
const user = await this.db.getUserByEmail(email);
const recoveryToken = await this.db.requestRecoveryToken(email);
const name = user.firstName;
const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const html = await this.emailService.buildEmail("passwordResetTemplate", {
name,
email,
url,
});
const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
return msgId;
};
validateRecovery = async (recoveryToken) => {
await this.db.validateRecoveryToken(recoveryToken);
};
resetPassword = async (password, recoveryToken) => {
const user = await this.db.resetPassword(password, recoveryToken);
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, appSettings);
return { user, token };
};
deleteUser = async (user) => {
const email = user?.email;
if (!email) {
throw new Error("No email in request");
}
const teamId = user?.teamId;
const userId = user?._id;
if (!teamId) {
throw new Error("No team ID in request");
}
if (!userId) {
throw new Error("No user ID in request");
}
const roles = user?.role;
if (roles.includes("demo")) {
throw new Error("Demo user cannot be deleted");
}
// 1. Find all the monitors associated with the team ID if superadmin
const result = await this.db.getMonitorsByTeamId({
teamId: teamId,
});
if (roles.includes("superadmin")) {
// 2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 &&
(await Promise.all(
result.monitors.map(async (monitor) => {
await this.jobQueue.deleteJob(monitor);
})
));
}
// 6. Delete the user by id
await this.db.deleteUser(userId);
};
getAllUsers = async () => {
const users = await this.db.getAllUsers();
return users;
};
getUserById = async (roles, userId) => {
const user = await this.db.getUserById(roles, userId);
return user;
};
editUserById = async (userId, user) => {
await this.db.editUserById(userId, user);
};
}
export default UserService;