Files
status-monitor/ui/src/services/utils.ts
2025-07-10 05:48:24 +02:00

69 lines
2.0 KiB
TypeScript

import type { UptimeMessage } from "@/services/types";
export function isAgentOnline(data: UptimeMessage): boolean {
const timeDiff = new Date().getTime() - new Date(data.last_seen).getTime();
return timeDiff < 10000;
}
export function formatTimestamp(timestamp: string) {
return new Date(timestamp).toLocaleTimeString();
}
export const formatUptime = (seconds: number): string => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) {
return `${days}d ${hours}h`;
} else if (hours > 0) {
return `${hours}h ${minutes}m`;
} else {
return `${minutes}m`;
}
};
export function formatRelativeTime(timestamp: string): string {
const now = new Date();
const past = new Date(timestamp);
const diffInSeconds = Math.floor((now.getTime() - past.getTime()) / 1000);
if (diffInSeconds < 5) {
return "now";
} else if (diffInSeconds < 60) {
return `${diffInSeconds}s ago`;
} else if (diffInSeconds < 3600) {
const minutes = Math.floor(diffInSeconds / 60);
return `${minutes}m ago`;
} else if (diffInSeconds < 86400) {
const hours = Math.floor(diffInSeconds / 3600);
return `${hours}h ago`;
} else {
const days = Math.floor(diffInSeconds / 86400);
return `${days}d ago`;
}
}
export function formatBytes(bytes: number | undefined): string {
if (!bytes || bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
export function calcPercentage(
value: number | undefined,
total: number | undefined,
): number {
if (value === undefined || total === undefined) return 0;
return (value / total) * 100;
}
export function formatPercentage(val: number | undefined) {
return `${(val ?? 0).toFixed(2)}%`;
}