add v2 services
This commit is contained in:
1 parent
35a712eafb
commit
68f4adfbfe
24 files changed
+3132
No files matched your search
@@ -0,0 +1,206 @@
|
||||
import bcrypt from "bcryptjs";
|
||||
import { User, Role, ITokenizedUser, Monitor, Check, NotificationChannel } from "../../../db/v2/models/index.js";
|
||||
import ApiError from "../../../utils/ApiError.js";
|
||||
import { Types } from "mongoose";
|
||||
import { IJobQueue } from "../infrastructure/JobQueue.js";
|
||||
|
||||
export const PERMISSIONS = {
|
||||
users: {
|
||||
all: "users.*",
|
||||
create: "users.create",
|
||||
view: "users.view",
|
||||
update: "users.update",
|
||||
delete: "users.delete",
|
||||
},
|
||||
|
||||
monitors: {
|
||||
all: "monitors.*",
|
||||
create: "monitors.create",
|
||||
view: "monitors.view",
|
||||
update: "monitors.update",
|
||||
delete: "monitors.delete",
|
||||
},
|
||||
notifications: {
|
||||
all: "notifications.*",
|
||||
create: "notifications.create",
|
||||
view: "notifications.view",
|
||||
update: "notifications.update",
|
||||
delete: "notifications.delete",
|
||||
},
|
||||
checks: {
|
||||
all: "checks.*",
|
||||
create: "checks.create",
|
||||
view: "checks.view",
|
||||
update: "checks.update",
|
||||
delete: "checks.delete",
|
||||
},
|
||||
statusPages: {
|
||||
all: "statusPages.*",
|
||||
create: "statusPages.create",
|
||||
view: "statusPages.view",
|
||||
update: "statusPages.update",
|
||||
delete: "statusPages.delete",
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_ROLES = [
|
||||
{
|
||||
name: "SuperAdmin",
|
||||
description: "Super admin with all permissions",
|
||||
permissions: ["*"],
|
||||
isSystem: true,
|
||||
},
|
||||
{
|
||||
name: "Admin",
|
||||
description: "Admin with full permissions",
|
||||
permissions: [PERMISSIONS.monitors.all, PERMISSIONS.users.all],
|
||||
isSystem: true,
|
||||
},
|
||||
{
|
||||
name: "Manager",
|
||||
description: "Can manage users",
|
||||
permissions: [PERMISSIONS.users.create, PERMISSIONS.users.update, PERMISSIONS.monitors.all],
|
||||
isSystem: true,
|
||||
},
|
||||
{
|
||||
name: "Member",
|
||||
description: "Basic team member",
|
||||
permissions: [PERMISSIONS.users.update, PERMISSIONS.monitors.create, PERMISSIONS.monitors.view, PERMISSIONS.monitors.update],
|
||||
isSystem: true,
|
||||
},
|
||||
];
|
||||
|
||||
export type RegisterData = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
password: string;
|
||||
roles?: Types.ObjectId[]; // Optional roles for invite-based registration
|
||||
};
|
||||
|
||||
export type LoginData = {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type AuthResult = ITokenizedUser;
|
||||
|
||||
export interface IAuthService {
|
||||
register(signupData: RegisterData): Promise<ITokenizedUser>;
|
||||
registerWithInvite(signupData: RegisterData): Promise<ITokenizedUser>;
|
||||
login(loginData: LoginData): Promise<ITokenizedUser>;
|
||||
cleanup(): Promise<void>;
|
||||
cleanMonitors(): Promise<void>;
|
||||
}
|
||||
|
||||
class AuthService implements IAuthService {
|
||||
private jobQueue: IJobQueue;
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
async register(signupData: RegisterData): Promise<ITokenizedUser> {
|
||||
const userCount = await User.countDocuments();
|
||||
|
||||
if (userCount > 0) {
|
||||
throw new Error("Registration is closed. Please request an invite.");
|
||||
}
|
||||
|
||||
const { email, firstName, lastName, password } = signupData;
|
||||
|
||||
// Create all default roles
|
||||
const rolePromises = DEFAULT_ROLES.map((roleData) =>
|
||||
new Role({
|
||||
...roleData,
|
||||
}).save()
|
||||
);
|
||||
const roles = await Promise.all(rolePromises);
|
||||
|
||||
// Hash password and create user
|
||||
const saltRounds = 12;
|
||||
const passwordHash = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
// Find admin role and assign to first user
|
||||
const superAdminRole = roles.find((role) => role.name === "SuperAdmin");
|
||||
|
||||
const user = new User({
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
passwordHash,
|
||||
roles: [superAdminRole!._id],
|
||||
});
|
||||
|
||||
const savedUser = await user.save();
|
||||
return {
|
||||
sub: savedUser._id.toString(),
|
||||
roles: savedUser.roles.map((role) => role.toString()),
|
||||
};
|
||||
}
|
||||
|
||||
async registerWithInvite(signupData: RegisterData): Promise<ITokenizedUser> {
|
||||
const { email, firstName, lastName, password, roles } = signupData;
|
||||
|
||||
const saltRounds = 12;
|
||||
const passwordHash = await bcrypt.hash(password, saltRounds);
|
||||
const user = new User({
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
passwordHash,
|
||||
roles: roles || [],
|
||||
});
|
||||
try {
|
||||
const savedUser = await user.save();
|
||||
return {
|
||||
sub: savedUser._id.toString(),
|
||||
roles: savedUser.roles.map((role) => role.toString()),
|
||||
};
|
||||
} catch (error: any) {
|
||||
if (error?.code === 11000) {
|
||||
const dupError = new ApiError("Email already in use", 409);
|
||||
dupError.stack = error?.stack;
|
||||
throw dupError;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async login(loginData: LoginData): Promise<ITokenizedUser> {
|
||||
const { email, password } = loginData;
|
||||
|
||||
// Find user by email
|
||||
const user = await User.findOne({ email });
|
||||
|
||||
if (!user) {
|
||||
throw new Error("Invalid email or password");
|
||||
}
|
||||
|
||||
// Check password
|
||||
const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!isPasswordValid) {
|
||||
throw new Error("Invalid email or password");
|
||||
}
|
||||
|
||||
return {
|
||||
sub: user._id.toString(),
|
||||
roles: user.roles.map((role) => role.toString()),
|
||||
};
|
||||
}
|
||||
|
||||
async cleanup() {
|
||||
await User.deleteMany({});
|
||||
await Role.deleteMany({});
|
||||
await Monitor.deleteMany({});
|
||||
await Check.deleteMany({});
|
||||
await NotificationChannel.deleteMany({});
|
||||
await this.jobQueue.flush();
|
||||
}
|
||||
|
||||
async cleanMonitors() {
|
||||
await Monitor.deleteMany({});
|
||||
await Check.deleteMany({});
|
||||
}
|
||||
}
|
||||
|
||||
export default AuthService;
|
||||
@@ -0,0 +1,132 @@
|
||||
import { json } from "stream/consumers";
|
||||
import { ICheck, Check, Monitor } from "../../../db/v2/models/index.js";
|
||||
import type { ISystemInfo, ICaptureInfo } from "../../../db/v2/models/index.js";
|
||||
import { MonitorType } from "../../../db/v2/models/monitors/Monitor.js";
|
||||
import { StatusResponse } from "../infrastructure/NetworkService.js";
|
||||
import type { ICapturePayload, ILighthousePayload } from "../infrastructure/NetworkService.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
export interface ICheckService {
|
||||
buildCheck: (statusResponse: StatusResponse, type: MonitorType) => Promise<ICheck>;
|
||||
cleanupOrphanedChecks: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
class CheckService implements ICheckService {
|
||||
private isCapturePayload = (payload: any): payload is ICapturePayload => {
|
||||
if (!payload || typeof payload !== "object") return false;
|
||||
|
||||
if (!("data" in payload) || typeof payload.data !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = payload.data as Partial<ISystemInfo>;
|
||||
if (!data.cpu || typeof data.cpu !== "object" || typeof data.cpu.usage_percent !== "number") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!data.memory || typeof data.memory !== "object" || typeof data.memory.usage_percent !== "number") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (data.disk && !Array.isArray(data.disk)) {
|
||||
return false;
|
||||
}
|
||||
if (data.net && !Array.isArray(data.net)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!("capture" in payload) || typeof payload.capture !== "object") return false;
|
||||
const capture = payload.capture as Record<string, any>;
|
||||
if (typeof capture.version !== "string" || typeof capture.mode !== "string") return false;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
private isPagespeedPayload = (payload: any): payload is ILighthousePayload => {
|
||||
if (!payload || typeof payload !== "object") return false;
|
||||
|
||||
if (!("lighthouseResult" in payload) || typeof payload.lighthouseResult !== "object") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
private buildBaseCheck = (statusResponse: StatusResponse) => {
|
||||
const monitorId = new mongoose.Types.ObjectId(statusResponse.monitorId);
|
||||
const check = new Check({
|
||||
monitorId: monitorId,
|
||||
type: statusResponse?.type,
|
||||
status: statusResponse?.status,
|
||||
message: statusResponse?.message,
|
||||
responseTime: statusResponse?.responseTime,
|
||||
timings: statusResponse?.timings,
|
||||
});
|
||||
return check;
|
||||
};
|
||||
|
||||
private buildInfrastructureCheck = (statusResponse: StatusResponse<ICapturePayload>) => {
|
||||
if (!this.isCapturePayload(statusResponse.payload)) {
|
||||
throw new Error("Invalid payload for infrastructure monitor");
|
||||
}
|
||||
const check = this.buildBaseCheck(statusResponse);
|
||||
check.system = statusResponse.payload.data;
|
||||
check.capture = statusResponse.payload.capture;
|
||||
return check;
|
||||
};
|
||||
|
||||
private buildPagespeedCheck = (statusResponse: StatusResponse<ILighthousePayload>) => {
|
||||
if (!this.isPagespeedPayload(statusResponse.payload)) {
|
||||
throw new Error("Invalid payload for pagespeed monitor");
|
||||
}
|
||||
const check = this.buildBaseCheck(statusResponse);
|
||||
const lighthouseResult = statusResponse?.payload?.lighthouseResult;
|
||||
check.lighthouse = {
|
||||
accessibility: lighthouseResult?.categories?.accessibility?.score || 0,
|
||||
bestPractices: lighthouseResult?.categories?.["best-practices"]?.score || 0,
|
||||
seo: lighthouseResult?.categories?.seo?.score || 0,
|
||||
performance: lighthouseResult?.categories?.performance?.score || 0,
|
||||
audits: {
|
||||
cls: lighthouseResult?.audits?.["cumulative-layout-shift"] || {},
|
||||
si: lighthouseResult?.audits?.["speed-index"] || {},
|
||||
fcp: lighthouseResult?.audits?.["first-contentful-paint"] || {},
|
||||
lcp: lighthouseResult?.audits?.["largest-contentful-paint"] || {},
|
||||
tbt: lighthouseResult?.audits?.["total-blocking-time"] || {},
|
||||
},
|
||||
};
|
||||
return check;
|
||||
};
|
||||
|
||||
buildCheck = async (statusResponse: StatusResponse, type: MonitorType): Promise<ICheck> => {
|
||||
switch (type) {
|
||||
case "infrastructure":
|
||||
return this.buildInfrastructureCheck(statusResponse as StatusResponse<ICapturePayload>);
|
||||
|
||||
case "pagespeed":
|
||||
return this.buildPagespeedCheck(statusResponse as StatusResponse<ILighthousePayload>);
|
||||
case "http":
|
||||
case "https":
|
||||
return this.buildBaseCheck(statusResponse);
|
||||
|
||||
case "ping":
|
||||
return this.buildBaseCheck(statusResponse);
|
||||
default:
|
||||
throw new Error(`Unsupported monitor type: ${type}`);
|
||||
}
|
||||
};
|
||||
|
||||
cleanupOrphanedChecks = async () => {
|
||||
try {
|
||||
const monitorIds = await Monitor.find().distinct("_id");
|
||||
const result = await Check.deleteMany({
|
||||
monitorId: { $nin: monitorIds },
|
||||
});
|
||||
console.log(`Deleted ${result.deletedCount} orphaned Checks.`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error cleaning up orphaned Checks:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default CheckService;
|
||||
@@ -0,0 +1,61 @@
|
||||
import crypto from "node:crypto";
|
||||
import { ITokenizedUser, IInvite, Invite } from "../../../db/v2/models/index.js";
|
||||
import ApiError from "../../../utils/ApiError.js";
|
||||
|
||||
export interface IInviteService {
|
||||
create: (tokenizedUser: ITokenizedUser, invite: IInvite) => Promise<{ token: string }>;
|
||||
getAll: () => Promise<IInvite[]>;
|
||||
get: (tokenHash: string) => Promise<IInvite>;
|
||||
delete: (id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class InviteService implements IInviteService {
|
||||
constructor() {}
|
||||
|
||||
create = async (tokenizedUser: ITokenizedUser, inviteData: IInvite) => {
|
||||
const token = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
try {
|
||||
const invite = await Invite.create({
|
||||
...inviteData,
|
||||
tokenHash,
|
||||
createdBy: tokenizedUser.sub,
|
||||
updatedBy: tokenizedUser.sub,
|
||||
});
|
||||
if (!invite) {
|
||||
throw new ApiError("Failed to create invite", 500);
|
||||
}
|
||||
return { token };
|
||||
} catch (error: any) {
|
||||
if (error?.code === 11000) {
|
||||
const dupError = new ApiError("Invite with this email already exists", 409);
|
||||
dupError.stack = error?.stack;
|
||||
throw dupError;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
get = async (token: string) => {
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
const invite = await Invite.findOne({ tokenHash });
|
||||
if (!invite) {
|
||||
throw new ApiError("Invite not found", 404);
|
||||
}
|
||||
return invite;
|
||||
};
|
||||
|
||||
getAll = async () => {
|
||||
return Invite.find();
|
||||
};
|
||||
|
||||
delete = async (id: string) => {
|
||||
const result = await Invite.deleteOne({ _id: id });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Invite not found", 404);
|
||||
}
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default InviteService;
|
||||
@@ -0,0 +1,141 @@
|
||||
import { ITokenizedUser, IMaintenance, Maintenance } from "../../../db/v2/models/index.js";
|
||||
import ApiError from "../../../utils/ApiError.js";
|
||||
|
||||
export interface IMaintenanceService {
|
||||
create: (
|
||||
tokenizedUser: ITokenizedUser,
|
||||
|
||||
maintenance: IMaintenance
|
||||
) => Promise<IMaintenance>;
|
||||
getAll: () => Promise<IMaintenance[]>;
|
||||
get: (id: string) => Promise<IMaintenance>;
|
||||
toggleActive: (tokenizedUser: ITokenizedUser, id: string) => Promise<IMaintenance>;
|
||||
update: (tokenizedUser: ITokenizedUser, id: string, updateData: Partial<IMaintenance>) => Promise<IMaintenance>;
|
||||
delete: (id: string) => Promise<boolean>;
|
||||
isInMaintenance: (monitorId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
type MaintenanceCache = Map<string, IMaintenance[]>;
|
||||
|
||||
class MaintenanceService implements IMaintenanceService {
|
||||
private maintenanceCache: MaintenanceCache;
|
||||
private lastRefresh: number;
|
||||
private CACHE_TTL_MS = 60 * 1000;
|
||||
|
||||
constructor() {
|
||||
this.maintenanceCache = new Map();
|
||||
this.lastRefresh = 0;
|
||||
}
|
||||
|
||||
create = async (tokenizedUser: ITokenizedUser, maintenanceData: IMaintenance) => {
|
||||
const maintenance = await Maintenance.create({
|
||||
...maintenanceData,
|
||||
createdBy: tokenizedUser.sub,
|
||||
updatedBy: tokenizedUser.sub,
|
||||
});
|
||||
return maintenance;
|
||||
};
|
||||
|
||||
get = async (id: string) => {
|
||||
const maintenance = await Maintenance.findById(id);
|
||||
if (!maintenance) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return maintenance;
|
||||
};
|
||||
|
||||
getAll = async () => {
|
||||
return Maintenance.find();
|
||||
};
|
||||
|
||||
toggleActive = async (tokenizedUser: ITokenizedUser, id: string) => {
|
||||
const updatedMaintenance = await Maintenance.findOneAndUpdate(
|
||||
{ _id: id },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
updatedBy: tokenizedUser.sub,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
if (!updatedMaintenance) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return updatedMaintenance;
|
||||
};
|
||||
|
||||
update = async (tokenizedUser: ITokenizedUser, id: string, updateData: Partial<IMaintenance>) => {
|
||||
const allowedFields: (keyof IMaintenance)[] = ["name", "monitors", "startTime", "endTime", "isActive"];
|
||||
const safeUpdate: Partial<IMaintenance> = {};
|
||||
for (const field of allowedFields) {
|
||||
if (updateData[field] !== undefined) {
|
||||
(safeUpdate as any)[field] = updateData[field];
|
||||
}
|
||||
}
|
||||
|
||||
const updatedMaintenance = await Maintenance.findByIdAndUpdate(
|
||||
id,
|
||||
{
|
||||
$set: {
|
||||
...safeUpdate,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: tokenizedUser.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedMaintenance) {
|
||||
throw new ApiError("Failed to update maintenance", 500);
|
||||
}
|
||||
|
||||
return updatedMaintenance;
|
||||
};
|
||||
|
||||
delete = async (id: string) => {
|
||||
const result = await Maintenance.deleteOne({ _id: id });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
|
||||
private refreshCache = async () => {
|
||||
const now = new Date();
|
||||
|
||||
const activeMaintenances = await Maintenance.find({
|
||||
isActive: true,
|
||||
startTime: { $lte: now },
|
||||
endTime: { $gte: now },
|
||||
}).lean();
|
||||
|
||||
// Reset cache
|
||||
const newCache = new Map();
|
||||
|
||||
for (const m of activeMaintenances) {
|
||||
for (const monitorId of m.monitors) {
|
||||
const key = monitorId.toString();
|
||||
if (!newCache.has(key)) newCache.set(key, []);
|
||||
newCache.get(key)!.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
this.maintenanceCache = newCache;
|
||||
this.lastRefresh = Date.now();
|
||||
};
|
||||
|
||||
isInMaintenance = async (monitorId: string) => {
|
||||
const now = Date.now();
|
||||
if (now - this.lastRefresh > this.CACHE_TTL_MS) {
|
||||
await this.refreshCache();
|
||||
}
|
||||
const maintenances = this.maintenanceCache.get(monitorId) || [];
|
||||
return maintenances.length > 0;
|
||||
};
|
||||
}
|
||||
|
||||
export default MaintenanceService;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { MonitorStats } from "../../../db/v2/models/index.js";
|
||||
import { Monitor } from "../../../db/v2/models/index.js";
|
||||
export interface IMonitorStatsService {
|
||||
cleanupOrphanedMonitorStats: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
class MonitorStatsService implements IMonitorStatsService {
|
||||
constructor() {}
|
||||
|
||||
async cleanupOrphanedMonitorStats() {
|
||||
try {
|
||||
const monitorIds = await Monitor.find().distinct("_id");
|
||||
const result = await MonitorStats.deleteMany({
|
||||
monitorId: { $nin: monitorIds },
|
||||
});
|
||||
console.log(`Deleted ${result.deletedCount} orphaned MonitorStats.`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error cleaning up orphaned MonitorStats:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default MonitorStatsService;
|
||||
@@ -0,0 +1,100 @@
|
||||
import { ITokenizedUser, INotificationChannel, NotificationChannel, Monitor } from "../../../db/v2/models/index.js";
|
||||
import ApiError from "../../../utils/ApiError.js";
|
||||
|
||||
export interface INotificationChannelService {
|
||||
create: (
|
||||
tokenizedUser: ITokenizedUser,
|
||||
|
||||
notificationChannel: INotificationChannel
|
||||
) => Promise<INotificationChannel>;
|
||||
getAll: () => Promise<INotificationChannel[]>;
|
||||
get: (id: string) => Promise<INotificationChannel>;
|
||||
toggleActive: (tokenizedUser: ITokenizedUser, id: string) => Promise<INotificationChannel>;
|
||||
update: (tokenizedUser: ITokenizedUser, id: string, updateData: Partial<INotificationChannel>) => Promise<INotificationChannel>;
|
||||
delete: (id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class NotificationChannelService implements INotificationChannelService {
|
||||
constructor() {}
|
||||
|
||||
create = async (tokenizedUser: ITokenizedUser, notificationChannelData: INotificationChannel) => {
|
||||
const notificationChannel = await NotificationChannel.create({
|
||||
...notificationChannelData,
|
||||
createdBy: tokenizedUser.sub,
|
||||
updatedBy: tokenizedUser.sub,
|
||||
});
|
||||
return notificationChannel;
|
||||
};
|
||||
|
||||
get = async (id: string) => {
|
||||
const channel = await NotificationChannel.findById(id);
|
||||
if (!channel) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
return channel;
|
||||
};
|
||||
|
||||
getAll = async () => {
|
||||
return NotificationChannel.find();
|
||||
};
|
||||
|
||||
toggleActive = async (tokenizedUser: ITokenizedUser, id: string) => {
|
||||
const updatedChannel = await NotificationChannel.findOneAndUpdate(
|
||||
{ _id: id },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
updatedBy: tokenizedUser.sub,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
if (!updatedChannel) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
return updatedChannel;
|
||||
};
|
||||
|
||||
update = async (tokenizedUser: ITokenizedUser, id: string, updateData: Partial<INotificationChannel>) => {
|
||||
const allowedFields: (keyof INotificationChannel)[] = ["name", "config", "isActive"];
|
||||
const safeUpdate: Partial<INotificationChannel> = {};
|
||||
for (const field of allowedFields) {
|
||||
if (updateData[field] !== undefined) {
|
||||
(safeUpdate as any)[field] = updateData[field];
|
||||
}
|
||||
}
|
||||
|
||||
const updatedChannel = await NotificationChannel.findByIdAndUpdate(
|
||||
id,
|
||||
{
|
||||
$set: {
|
||||
...safeUpdate,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: tokenizedUser.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedChannel) {
|
||||
throw new ApiError("Failed to update notification channel", 500);
|
||||
}
|
||||
|
||||
return updatedChannel;
|
||||
};
|
||||
|
||||
delete = async (id: string) => {
|
||||
const result = await NotificationChannel.deleteOne({ _id: id });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
|
||||
await Monitor.updateMany({ notificationChannels: id }, { $pull: { notificationChannels: id } });
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default NotificationChannelService;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { IJobQueue } from "../infrastructure/JobQueue.js";
|
||||
|
||||
class QueueService {
|
||||
private jobQueue: IJobQueue;
|
||||
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
async getMetrics() {
|
||||
return await this.jobQueue.getMetrics();
|
||||
}
|
||||
|
||||
async getJobs() {
|
||||
return await this.jobQueue.getJobs();
|
||||
}
|
||||
|
||||
async flush() {
|
||||
return await this.jobQueue.flush();
|
||||
}
|
||||
}
|
||||
|
||||
export default QueueService;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IUser, User } from "../../../db/v2/models/index.js";
|
||||
|
||||
export interface IUserService {
|
||||
getAllUsers(): Promise<IUser[]>;
|
||||
}
|
||||
|
||||
class UserService implements IUserService {
|
||||
async getAllUsers(): Promise<IUser[]> {
|
||||
return await User.find();
|
||||
}
|
||||
}
|
||||
|
||||
export default UserService;
|
||||
Reference in new issue
Block a user