refactoring
This commit is contained in:
1 parent
e090d3cfd3
commit
7a6b0d5da4
19 files changed
+699
-116
No files matched your search
@@ -0,0 +1,10 @@
|
||||
import type { LatestChecksMap } from "@/repositories/checks/MongoChecksRepistory.js";
|
||||
|
||||
export interface IChecksRepository {
|
||||
// create
|
||||
// single fetch
|
||||
// collection fetch
|
||||
findLatestChecksByMonitorIds(monitorIds: string[]): Promise<LatestChecksMap>;
|
||||
// update
|
||||
// delete
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { IChecksRepository } from "@/repositories/index.js";
|
||||
import type {
|
||||
Check,
|
||||
CheckAudits,
|
||||
CheckCaptureInfo,
|
||||
CheckCpuInfo,
|
||||
CheckDiskInfo,
|
||||
CheckErrorInfo,
|
||||
CheckHostInfo,
|
||||
CheckMemoryInfo,
|
||||
CheckMetadata,
|
||||
CheckNetworkInterfaceInfo,
|
||||
CheckTimings,
|
||||
} from "@/types/index.js";
|
||||
import { CheckModel, type CheckDocument } from "@/db/models/index.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
export type LatestChecksMap = Record<string, Check[]>;
|
||||
|
||||
class MongoChecksRepistory implements IChecksRepository {
|
||||
private toEntity = (doc: CheckDocument): Check => {
|
||||
const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value);
|
||||
};
|
||||
|
||||
const toDateString = (value?: Date | string | null): string => {
|
||||
if (!value) {
|
||||
return new Date(0).toISOString();
|
||||
}
|
||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||
};
|
||||
|
||||
const toOptionalDateString = (value?: Date | string | null): string | undefined => {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
return toDateString(value);
|
||||
};
|
||||
|
||||
const mapTimings = (timings?: CheckTimings): CheckTimings => {
|
||||
const phases = timings?.phases ?? {
|
||||
wait: 0,
|
||||
dns: 0,
|
||||
tcp: 0,
|
||||
tls: 0,
|
||||
request: 0,
|
||||
firstByte: 0,
|
||||
download: 0,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
return {
|
||||
start: timings?.start ?? 0,
|
||||
socket: timings?.socket ?? 0,
|
||||
lookup: timings?.lookup ?? 0,
|
||||
connect: timings?.connect ?? 0,
|
||||
secureConnect: timings?.secureConnect ?? 0,
|
||||
upload: timings?.upload ?? 0,
|
||||
response: timings?.response ?? 0,
|
||||
end: timings?.end ?? 0,
|
||||
phases,
|
||||
};
|
||||
};
|
||||
|
||||
const mapCpu = (cpu?: CheckCpuInfo): CheckCpuInfo => ({
|
||||
physical_core: cpu?.physical_core ?? 0,
|
||||
logical_core: cpu?.logical_core ?? 0,
|
||||
frequency: cpu?.frequency ?? 0,
|
||||
temperature: cpu?.temperature ?? [],
|
||||
free_percent: cpu?.free_percent ?? 0,
|
||||
usage_percent: cpu?.usage_percent ?? 0,
|
||||
});
|
||||
|
||||
const mapMemory = (memory?: CheckMemoryInfo): CheckMemoryInfo => ({
|
||||
total_bytes: memory?.total_bytes ?? 0,
|
||||
available_bytes: memory?.available_bytes ?? 0,
|
||||
used_bytes: memory?.used_bytes ?? 0,
|
||||
usage_percent: memory?.usage_percent ?? 0,
|
||||
});
|
||||
|
||||
const mapHost = (host?: CheckHostInfo): CheckHostInfo => ({
|
||||
os: host?.os ?? "",
|
||||
platform: host?.platform ?? "",
|
||||
kernel_version: host?.kernel_version ?? "",
|
||||
});
|
||||
|
||||
const mapCapture = (capture?: CheckCaptureInfo): CheckCaptureInfo => ({
|
||||
version: capture?.version ?? "",
|
||||
mode: capture?.mode ?? "",
|
||||
});
|
||||
|
||||
const mapDisks = (disks?: CheckDiskInfo[]): CheckDiskInfo[] =>
|
||||
(disks ?? []).map((disk) => ({
|
||||
device: disk?.device ?? "",
|
||||
mountpoint: disk?.mountpoint ?? "",
|
||||
read_speed_bytes: disk?.read_speed_bytes ?? 0,
|
||||
write_speed_bytes: disk?.write_speed_bytes ?? 0,
|
||||
total_bytes: disk?.total_bytes ?? 0,
|
||||
free_bytes: disk?.free_bytes ?? 0,
|
||||
usage_percent: disk?.usage_percent ?? 0,
|
||||
}));
|
||||
|
||||
const mapErrors = (errors?: CheckErrorInfo[]): CheckErrorInfo[] =>
|
||||
(errors ?? []).map((error) => ({
|
||||
metric: error?.metric ?? [],
|
||||
err: error?.err ?? "",
|
||||
}));
|
||||
|
||||
const mapNet = (net?: CheckNetworkInterfaceInfo[]): CheckNetworkInterfaceInfo[] =>
|
||||
(net ?? []).map((iface) => ({
|
||||
name: iface?.name ?? "",
|
||||
bytes_sent: iface?.bytes_sent ?? 0,
|
||||
bytes_recv: iface?.bytes_recv ?? 0,
|
||||
packets_sent: iface?.packets_sent ?? 0,
|
||||
packets_recv: iface?.packets_recv ?? 0,
|
||||
err_in: iface?.err_in ?? 0,
|
||||
err_out: iface?.err_out ?? 0,
|
||||
drop_in: iface?.drop_in ?? 0,
|
||||
drop_out: iface?.drop_out ?? 0,
|
||||
fifo_in: iface?.fifo_in ?? 0,
|
||||
fifo_out: iface?.fifo_out ?? 0,
|
||||
}));
|
||||
|
||||
const mapAudits = (audits?: CheckAudits): CheckAudits | undefined => {
|
||||
if (!audits) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
cls: audits.cls ?? 0,
|
||||
si: audits.si ?? 0,
|
||||
fcp: audits.fcp ?? 0,
|
||||
lcp: audits.lcp ?? 0,
|
||||
tbt: audits.tbt ?? 0,
|
||||
};
|
||||
};
|
||||
|
||||
const mapMetadata = (metadata: CheckDocument["metadata"]): CheckMetadata => ({
|
||||
monitorId: toStringId(metadata.monitorId),
|
||||
teamId: toStringId(metadata.teamId),
|
||||
type: metadata.type,
|
||||
});
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
metadata: mapMetadata(doc.metadata),
|
||||
status: doc.status ?? false,
|
||||
responseTime: doc.responseTime ?? 0,
|
||||
timings: mapTimings(doc.timings),
|
||||
statusCode: doc.statusCode ?? 0,
|
||||
message: doc.message ?? "",
|
||||
ack: doc.ack ?? false,
|
||||
ackAt: toOptionalDateString(doc.ackAt),
|
||||
expiry: toDateString(doc.expiry),
|
||||
cpu: mapCpu(doc.cpu),
|
||||
memory: mapMemory(doc.memory),
|
||||
disk: mapDisks(doc.disk),
|
||||
host: mapHost(doc.host),
|
||||
errors: mapErrors(doc.errors),
|
||||
capture: mapCapture(doc.capture),
|
||||
net: mapNet(doc.net),
|
||||
accessibility: doc.accessibility,
|
||||
bestPractices: doc.bestPractices,
|
||||
seo: doc.seo,
|
||||
performance: doc.performance,
|
||||
audits: mapAudits(doc.audits),
|
||||
__v: doc.__v ?? 0,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
findLatestChecksByMonitorIds = async (monitorIds: string[]): Promise<LatestChecksMap> => {
|
||||
const mongoIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const checkMap = await CheckModel.aggregate([
|
||||
{
|
||||
$match: {
|
||||
"metadata.monitorId": { $in: mongoIds },
|
||||
},
|
||||
},
|
||||
{ $sort: { createdAt: -1 } },
|
||||
{
|
||||
$group: {
|
||||
_id: "$metadata.monitorId",
|
||||
latestChecks: { $push: "$$ROOT" },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
latestChecks: { $slice: [{ $ifNull: ["$latestChecks", []] }, 25] },
|
||||
},
|
||||
},
|
||||
]);
|
||||
return checkMap.reduce<LatestChecksMap>((acc, cm) => {
|
||||
acc[cm._id.toString()] = cm.latestChecks.map((c: CheckDocument) => this.toEntity(c));
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoChecksRepistory;
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from "@/repositories/monitors/IMonitorsRepository.js";
|
||||
export { default as MongoMonitorsRepository } from "@/repositories/monitors/MongoMonitorsRepository.js";
|
||||
|
||||
export * from "@/repositories/checks/IChecksRepository.js";
|
||||
export { default as MongoChecksRepository } from "@/repositories/checks/MongoChecksRepistory.js";
|
||||
@@ -1,9 +1,24 @@
|
||||
import type { Monitor } from "@/types/index.js";
|
||||
import { type MonitorType, type Monitor } from "@/types/index.js";
|
||||
|
||||
export interface TeamQueryConfig {
|
||||
limit?: number;
|
||||
type?: MonitorType | MonitorType[];
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
filter?: string;
|
||||
field?: string;
|
||||
order?: "asc" | "desc";
|
||||
}
|
||||
|
||||
export interface IMonitorsRepository {
|
||||
// create
|
||||
// single fetch
|
||||
// collection fetch
|
||||
findAll(): Promise<Monitor[] | null>;
|
||||
findByTeamId(teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null>;
|
||||
// update
|
||||
// delete
|
||||
|
||||
// counts
|
||||
findMonitorCountByTeamIdAndType(teamId: string, config: TeamQueryConfig): Promise<number>;
|
||||
}
|
||||
@@ -1,5 +1,125 @@
|
||||
import { MonitorModel } from "@/db/models/index.js";
|
||||
import type { MonitorDocument } from "@/db/models/Monitor.js";
|
||||
import type { Monitor, MonitorType } from "@/types/monitor.js";
|
||||
import mongoose, { type FilterQuery } from "mongoose";
|
||||
import type { IMonitorsRepository, TeamQueryConfig } from "./IMonitorsRepository.js";
|
||||
|
||||
class MongoMonitorsRepository implements IMonitorsRepository {
|
||||
findAll = async () => {
|
||||
return null;
|
||||
findAll = async (): Promise<Monitor[] | null> => {
|
||||
const documents = await MonitorModel.find().exec();
|
||||
return this.mapDocuments(documents);
|
||||
};
|
||||
|
||||
findByTeamId = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null> => {
|
||||
const { page = 0, rowsPerPage = 25, filter, field = "createdAt", order = "desc", type, limit } = config ?? {};
|
||||
|
||||
const query: Record<string, unknown> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
|
||||
if (type !== undefined) {
|
||||
query.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
if (filter !== undefined) {
|
||||
switch (field) {
|
||||
case "name":
|
||||
query.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
|
||||
break;
|
||||
case "isActive":
|
||||
query.isActive = filter === "true";
|
||||
break;
|
||||
case "status":
|
||||
query.status = filter === "true";
|
||||
break;
|
||||
case "type":
|
||||
query.type = filter;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sort = { [field]: order === "asc" ? 1 : -1 } as const;
|
||||
const skip = Math.max(page, 0) * rowsPerPage;
|
||||
const limitValue = limit ?? rowsPerPage;
|
||||
|
||||
const documents = await MonitorModel.find(query).sort(sort).skip(skip).limit(limitValue).exec();
|
||||
|
||||
return this.mapDocuments(documents);
|
||||
};
|
||||
|
||||
findMonitorCountByTeamIdAndType = async (teamId: string, config?: TeamQueryConfig): Promise<number> => {
|
||||
const { type } = config ?? {};
|
||||
|
||||
const query: FilterQuery<MonitorDocument> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
|
||||
if (type !== undefined) {
|
||||
query.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
const count = await MonitorModel.countDocuments(query);
|
||||
return count;
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: MonitorDocument[]): Monitor[] | null => {
|
||||
if (!documents?.length) {
|
||||
return null;
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toEntity = (doc: MonitorDocument): Monitor => {
|
||||
const toStringId = (value: unknown): string => {
|
||||
if (value instanceof mongoose.Types.ObjectId) {
|
||||
return value.toString();
|
||||
}
|
||||
return value?.toString() ?? "";
|
||||
};
|
||||
|
||||
const toDateString = (value: Date | string): string => {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
const notificationIds = (doc.notifications ?? []).map((notification) => toStringId(notification));
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
userId: toStringId(doc.userId),
|
||||
teamId: toStringId(doc.teamId),
|
||||
name: doc.name,
|
||||
description: doc.description ?? undefined,
|
||||
status: doc.status ?? undefined,
|
||||
statusWindow: doc.statusWindow ?? [],
|
||||
statusWindowSize: doc.statusWindowSize,
|
||||
statusWindowThreshold: doc.statusWindowThreshold,
|
||||
type: doc.type,
|
||||
ignoreTlsErrors: doc.ignoreTlsErrors,
|
||||
jsonPath: doc.jsonPath ?? undefined,
|
||||
expectedValue: doc.expectedValue ?? undefined,
|
||||
matchMethod: doc.matchMethod ?? undefined,
|
||||
url: doc.url,
|
||||
port: doc.port ?? undefined,
|
||||
isActive: doc.isActive,
|
||||
interval: doc.interval,
|
||||
uptimePercentage: doc.uptimePercentage ?? undefined,
|
||||
notifications: notificationIds,
|
||||
secret: doc.secret ?? undefined,
|
||||
thresholds: doc.thresholds ?? undefined,
|
||||
alertThreshold: doc.alertThreshold,
|
||||
cpuAlertThreshold: doc.cpuAlertThreshold,
|
||||
memoryAlertThreshold: doc.memoryAlertThreshold,
|
||||
diskAlertThreshold: doc.diskAlertThreshold,
|
||||
tempAlertThreshold: doc.tempAlertThreshold,
|
||||
selectedDisks: doc.selectedDisks ?? [],
|
||||
gameId: doc.gameId ?? undefined,
|
||||
group: doc.group ?? null,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoMonitorsRepository;
|
||||
Reference in new issue
Block a user