Files
UDN/utility.ts
T

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-07-08 21:13:56 +02:00
import { PACKAGE_FILE, STATIC_DIR, WS } from ".";
2024-07-08 18:02:08 +02:00
2024-07-05 12:48:42 +02:00
import Colors from "colors";
2024-07-05 16:04:12 +02:00
import Fs from "fs/promises";
2024-07-08 18:02:08 +02:00
import Path from "path";
import { WebSocketMessage } from "./websocket-handler";
2024-07-05 12:48:42 +02:00
2024-07-05 16:04:12 +02:00
// CONFIG
2024-07-07 18:16:28 +02:00
const STAT_INDENT = 25;
2024-07-05 16:04:12 +02:00
2024-07-07 18:20:37 +02:00
// MISC
export function doIfIsString(data: any, cb: (data: string) => void): void {
if (typeof data != "string" || data == "") return;
cb(data);
2024-07-05 00:15:00 +02:00
}
2024-07-05 12:48:42 +02:00
2024-07-07 18:20:37 +02:00
export async function getVersionNumber(): Promise<string> {
try {
const packageString = await Bun.file(PACKAGE_FILE).text();
const packageObject = JSON.parse(packageString);
return packageObject.version;
} catch {
return "unknown";
}
2024-07-07 18:20:37 +02:00
}
2024-07-08 18:02:08 +02:00
// SERVER
export function createFileResponse(requestPath: string): Response {
const fullPath = Path.join(STATIC_DIR, requestPath);
return new Response(Bun.file(fullPath));
2024-07-08 18:02:08 +02:00
}
2024-07-07 18:16:28 +02:00
// OUTPUT
2024-07-05 16:04:12 +02:00
async function writeToLogFile(message: string): Promise<void> {
await Fs.appendFile("logs", `${message}\n`);
2024-07-05 16:04:12 +02:00
}
2024-07-07 18:16:28 +02:00
// stats
export function writeStatString(label: string, value: string): void {
console.log(
`${label.padEnd(STAT_INDENT, " ")} ${Colors.bold.green(value)}`,
);
2024-07-05 16:04:12 +02:00
}
2024-07-07 18:16:28 +02:00
export function writeStatNumber(label: string, value: number): void {
console.log(
`${label.padEnd(STAT_INDENT, " ")} ${Colors.bold.blue(value.toString())}`,
);
2024-07-05 16:04:12 +02:00
}
2024-07-07 18:16:28 +02:00
// logging
export function writeError(message: any): void {
console.log(Colors.bold.red(message));
writeToLogFile(message);
2024-07-05 16:04:12 +02:00
}
export function writeSuccess(message: string): void {
console.log(Colors.bold.green(message));
writeToLogFile(message);
2024-07-05 16:04:12 +02:00
}
2024-07-07 18:16:28 +02:00
// MESSAGES
2024-07-05 16:04:12 +02:00
export function stringifyMessage(messageObject: WebSocketMessage): string {
return JSON.stringify(messageObject);
2024-07-05 13:17:19 +02:00
}
2024-07-05 16:04:12 +02:00
export function parseMessage(messageString: string): Object {
return JSON.parse(messageString);
}