Add name/roblox change support

This commit is contained in:
2024-03-05 23:37:51 -05:00
parent 5fe23184c9
commit 2f8ff3b3cc
2 changed files with 238 additions and 78 deletions

View File

@ -1,4 +1,4 @@
import { jsonError } from "../../../common.js";
import { jsonError, jsonResponse } from "../../../common.js";
export async function onRequestDelete(context: RequestContext) {
let body: { id?: string } = {};
@ -28,6 +28,62 @@ export async function onRequestDelete(context: RequestContext) {
});
}
export async function onRequestPatch(context: RequestContext) {
let body: { id?: string; name?: string; roblox_username?: string } = {};
try {
body = await context.request.json();
} catch {
return jsonError("Invalid body", 400);
}
if (typeof body.name !== "string" && typeof body.roblox_username !== "string")
return jsonError("At least one property must be provided", 400);
const updates = [];
if (body.name?.length) updates.push({ query: "name = ?", value: body.name });
if (typeof body.roblox_username === "string" && body.roblox_username) {
const robloxResolveResp = await fetch(
"https://users.roblox.com/v1/usernames/users",
{
body: JSON.stringify({
excludeBannedUsers: true,
usernames: [body.roblox_username],
}),
headers: {
"content-type": "application/json",
},
method: "POST",
},
);
const { data } = (await robloxResolveResp.json()) as {
data: { [k: string]: any }[];
};
if (!data.length)
return jsonError("No Roblox user exists with that name", 400);
updates.push({ query: "roblox_id = ?", value: data[0].id });
}
await context.env.D1.prepare(
`UPDATE et_members
SET (${updates.join(", ")});`,
)
.bind(...updates.map((u) => u.value))
.run();
return jsonResponse(
JSON.stringify({
name: body.name,
roblox_id: updates.find((u) => typeof u.value === "number")?.value,
}),
);
}
export async function onRequestPost(context: RequestContext) {
const { id, name, roblox_username } = context.data.body;