2024-10-14 21:59:35 -04:00
|
|
|
import { fileURLToPath } from 'url';
|
|
|
|
import { dirname, join } from 'path';
|
|
|
|
import { readFileSync } from 'fs';
|
2024-10-14 22:31:47 -04:00
|
|
|
import { db } from '@server/db';
|
|
|
|
import { sites } from './schema';
|
|
|
|
import { eq, and } from 'drizzle-orm';
|
2024-10-14 21:59:35 -04:00
|
|
|
|
|
|
|
// Get the directory name of the current module
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
|
|
const __dirname = dirname(__filename);
|
|
|
|
|
|
|
|
// Load the names from the names.json file
|
|
|
|
const file = join(__dirname, 'names.json');
|
|
|
|
export const names = JSON.parse(readFileSync(file, 'utf-8'));
|
|
|
|
|
2024-10-14 22:31:47 -04:00
|
|
|
export async function getUniqueName(orgId: string): Promise<string> {
|
|
|
|
let loops = 0;
|
|
|
|
while (true) {
|
|
|
|
if (loops > 100) {
|
|
|
|
throw new Error('Could not generate a unique name');
|
|
|
|
}
|
|
|
|
|
|
|
|
const name = generateName();
|
2024-10-14 22:33:51 -04:00
|
|
|
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 function generateName(): string {
|
2024-10-14 21:59:35 -04:00
|
|
|
return (
|
2024-10-14 22:26:32 -04:00
|
|
|
names.descriptors[Math.floor(Math.random() * names.descriptors.length)] + "-" +
|
|
|
|
names.animals[Math.floor(Math.random() * names.animals.length)]
|
|
|
|
).toLowerCase().replace(/\s/g, '-');
|
2024-10-14 21:59:35 -04:00
|
|
|
}
|