-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathroute.ts
More file actions
64 lines (52 loc) · 2.1 KB
/
Copy pathroute.ts
File metadata and controls
64 lines (52 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { validateUsername } from "@/lib/validations/username";
import { isReservedUsername } from '@/lib/reservedUsernames';
async function isAvailable(username: string): Promise<boolean> {
const [user, alias] = await Promise.all([
prisma.user.findUnique({ where: { username } }),
prisma.userAlias.findUnique({ where: { username } }),
]);
return !user && !alias;
}
if (isReservedUsername(username)) {
return NextResponse.json(
{ available: false, reason: 'This username is reserved and cannot be claimed.' },
{ status: 200 } // return 200 so the UI can show the message without erroring
);
}
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const username = searchParams.get("username")?.toLowerCase();
if (!username) {
return NextResponse.json({ available: false, error: "Username is required" });
}
const validation = validateUsername(username);
if (!validation.valid) {
return NextResponse.json({ available: false, error: validation.error });
}
const available = await isAvailable(username);
if (available) {
return NextResponse.json({ available: true });
}
const year = new Date().getFullYear().toString().slice(-2);
const short = username.slice(0, 5);
const abbr = username.replace(/[aeiou]/gi, "").slice(0, 6) || short;
const rand = Math.floor(10 + Math.random() * 90);
const candidates = [...new Set([
abbr !== username ? abbr : null,
`${username}dev`,
`the${username}`,
`${username}hq`,
`i${username}`,
`${short}${year}`,
`${username}${year}`,
`${username}${rand}`,
].filter(Boolean) as string[])].filter((candidate) => validateUsername(candidate).valid);
const suggestions: string[] = [];
for (const candidate of candidates) {
if (await isAvailable(candidate)) suggestions.push(candidate);
if (suggestions.length === 5) break;
}
return NextResponse.json({ available: false, suggestions });
}