fosrl.pangolin/server/db/names.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

import { join } from "path";
import { readFileSync } from "fs";
import { db } from "@server/db";
import { exitNodes, sites } from "./schema";
import { eq, and } from "drizzle-orm";
2025-01-01 21:41:31 -05:00
import { __DIRNAME } from "@server/lib/consts";
2024-10-14 21:59:35 -04:00
// Load the names from the names.json file
2024-10-26 17:02:11 -04:00
const dev = process.env.ENVIRONMENT !== "prod";
let file;
if (!dev) {
2025-01-04 20:22:01 -05:00
file = join(__DIRNAME, "names.json");
2024-10-26 17:02:11 -04:00
} else {
2025-01-01 21:41:31 -05:00
file = join("server/db/names.json");
2024-10-26 17:02:11 -04:00
}
export const names = JSON.parse(readFileSync(file, "utf-8"));
2024-10-14 21:59:35 -04:00
export async function getUniqueSiteName(orgId: string): Promise<string> {
2024-10-14 22:31:47 -04:00
let loops = 0;
while (true) {
if (loops > 100) {
throw new Error("Could not generate a unique name");
2024-10-14 22:31:47 -04:00
}
const name = generateName();
const count = await db
.select({ niceId: sites.niceId, orgId: sites.orgId })
.from(sites)
.where(and(eq(sites.niceId, name), eq(sites.orgId, orgId)));
2024-10-14 22:31:47 -04:00
if (count.length === 0) {
return name;
}
loops++;
}
}
export async function getUniqueExitNodeEndpointName(): Promise<string> {
let loops = 0;
const count = await db
.select()
.from(exitNodes);
while (true) {
if (loops > 100) {
throw new Error("Could not generate a unique name");
}
const name = generateName();
for (const node of count) {
if (node.endpoint.includes(name)) {
loops++;
continue;
}
}
return name;
}
}
2024-10-14 22:31:47 -04:00
export function generateName(): string {
2024-10-14 21:59:35 -04:00
return (
names.descriptors[
Math.floor(Math.random() * names.descriptors.length)
] +
"-" +
2024-10-14 22:26:32 -04:00
names.animals[Math.floor(Math.random() * names.animals.length)]
)
.toLowerCase()
.replace(/\s/g, "-");
}