Compare commits

...

6 Commits

Author SHA1 Message Date
5c17f87f89 Migrate the rest of the easy stuff
All checks were successful
Test, Build, Deploy / Test, Build, and Deploy (push) Successful in 58s
Test, Build, Deploy / Create Sentry Release (push) Successful in 6s
2026-04-11 04:32:09 -04:00
48631e32be Finish rest of game appeal stuff 2026-04-11 04:29:25 -04:00
b60f211d7b Migrate report recall endpoint 2026-04-11 04:29:15 -04:00
1a891e5898 Even more migrations 2026-04-11 04:29:04 -04:00
7b72f815b0 More stuff to migrate 2026-04-11 04:28:45 -04:00
4860288d11 Oops need schema update 2026-04-11 04:28:11 -04:00
21 changed files with 365 additions and 293 deletions

View File

@@ -40,13 +40,15 @@ export async function loader({ context }: { context: RequestContext }) {
status: 403,
});
const { results } = await context.env.D1.prepare(
"SELECT destination, path FROM short_links WHERE user = ?;",
)
.bind(userId)
.all();
return results as Record<string, string>[];
return await context.data.prisma.shortLink.findMany({
select: {
destination: true,
path: true,
},
where: {
user: userId,
},
});
}
export default function () {

View File

@@ -1,4 +1,8 @@
import { jsonError } from "../../../common.js";
import {
Appeal,
PushNotification,
} from "../../../../generated/prisma/client.js";
export async function onRequestPost(context: RequestContext) {
const { pathname } = new URL(context.request.url);
@@ -20,22 +24,23 @@ export async function onRequestPost(context: RequestContext) {
context.data.targetId = id;
if (!pathname.endsWith("/ban")) {
const appeal: Record<string, any> | null = await context.env.D1.prepare(
"SELECT * FROM appeals WHERE id = ?;",
)
.bind(id)
.first();
const appeal: Appeal | null = await context.data.prisma.appeal.findUnique({
where: {
id: id,
},
});
if (!appeal) return jsonError("No appeal with that ID exists", 404);
appeal.user = JSON.parse(appeal.user);
context.data.appeal = appeal;
const pushNotificationData = await context.env.D1.prepare(
"SELECT token FROM push_notifications WHERE event_id = ? AND event_type = 'appeal';",
)
.bind(id)
.first();
const pushNotificationData: PushNotification | null =
await context.data.prisma.pushNotification.findUnique({
where: {
event_id: id,
event_type: "appeal",
},
});
if (pushNotificationData)
context.data.fcm_token = pushNotificationData.token;

View File

@@ -13,11 +13,12 @@ export async function onRequestPost(context: RequestContext) {
fcm_token,
);
await context.env.D1.prepare(
"DELETE FROM push_notifications WHERE event_id = ? AND event_type = 'appeal';",
)
.bind(appeal.id)
.run();
await context.data.prisma.pushNotification.delete({
where: {
event_id: appeal.id,
event_type: "appeal",
},
});
} else {
const emailResponse = await sendEmail(
appeal.user.email,
@@ -37,11 +38,8 @@ export async function onRequestPost(context: RequestContext) {
const { current_user: currentUser } = context.data;
await context.env.D1.prepare(
"UPDATE appeals SET approved = 1, user = json_remove(user, '$.email') WHERE id = ?;",
)
.bind(context.params.id)
.run();
await context.data.prisma
.$executeRaw`UPDATE appeals SET approved = TRUE, user = json_remove(user, '$.id') WHERE id = ${appeal.id};`;
await fetch(
`https://discord.com/api/v10/guilds/242263977986359297/bans/${appeal.user.id}`,

View File

@@ -6,9 +6,11 @@ export async function onRequestDelete(context: RequestContext) {
if (targetId.search(/^\d{16.19}$/) === -1)
return jsonError("Invalid target id", 400);
await context.env.D1.prepare("DELETE FROM appeal_bans WHERE user = ?;")
.bind(targetId)
.run();
await context.data.prisma.appealBan.delete({
where: {
user: targetId,
},
});
const { current_user: currentUser } = context.data;
@@ -46,11 +48,12 @@ export async function onRequestPost(context: RequestContext) {
if (targetId.search(/^\d{16,19}$/) === -1)
return jsonError("Invalid target id", 400);
await context.env.D1.prepare(
"INSERT INTO appeal_bans (created_at, created_by, user) VALUES (?, ?, ?);",
)
.bind(Date.now(), context.data.current_user.id, targetId)
.run();
await context.data.prisma.appealBan.create({
data: {
created_by: context.data.current_user.id,
user: targetId,
},
});
await fetch(context.env.APPEALS_WEBHOOK, {
body: JSON.stringify({

View File

@@ -6,11 +6,12 @@ export async function onRequestGet(context: RequestContext) {
if (
!currentUser.email ||
(await context.env.DATA.get("appeal_disabled")) ||
(await context.env.D1.prepare(
"SELECT id FROM appeals WHERE open = 1 AND user = ?;",
)
.bind(currentUser.id)
.first()) ||
(await context.data.prisma.appeal.findFirst({
where: {
approved: null,
user: currentUser.id,
},
})) ||
(await context.env.DATA.get(`blockedappeal_${currentUser.id}`))
)
return jsonResponse('{"can_appeal":false}');
@@ -47,18 +48,24 @@ export async function onRequestPost(context: RequestContext) {
if (
existingBlockedAppeal ||
(await context.env.D1.prepare(
"SELECT approved FROM appeals WHERE approved IS NULL AND json_extract(user, '$.id') = ?;",
)
.bind(currentUser.id)
.first())
(await context.data.prisma.appeal.findFirst({
where: {
approved: null,
user: {
path: "id",
equals: currentUser.id,
},
},
}))
)
return jsonError("Appeal already submitted", 403);
if (
await context.env.D1.prepare("SELECT * FROM appeal_bans WHERE user = ?;")
.bind(currentUser.id)
.first()
await context.data.prisma.appealBan.findUnique({
where: {
user: currentUser.id,
},
})
) {
await context.env.DATA.put(`blockedappeal_${currentUser.id}`, "1", {
metadata: { email: currentUser.email },
@@ -73,29 +80,28 @@ export async function onRequestPost(context: RequestContext) {
.randomUUID()
.replaceAll("-", "")}`;
await context.env.D1.prepare(
"INSERT INTO appeals (ban_reason, created_at, id, learned, reason_for_unban, user) VALUES (?, ?, ?, ?, ?, ?);",
)
.bind(
whyBanned,
Date.now(),
appealId,
await context.data.prisma.appeal.create({
data: {
ban_reason: whyBanned,
id: appealId,
learned,
whyUnban,
JSON.stringify({
reason_for_unban: whyUnban,
user: {
email: currentUser.email,
id: currentUser.id,
username: currentUser.username,
}),
)
.run();
},
},
});
if (typeof senderTokenId === "string") {
await context.env.D1.prepare(
"INSERT INTO push_notifications (created_at, event_id, event_type, token) VALUES (?, ?, 'appeal', ?)",
)
.bind(Date.now(), appealId, senderTokenId)
.run();
await context.data.prisma.pushNotification.create({
data: {
event_id: appealId,
event_type: "appeal",
token: senderTokenId,
},
});
}
await fetch(context.env.APPEALS_WEBHOOK, {

View File

@@ -14,13 +14,27 @@ export async function onRequestGet(context: RequestContext) {
if (currentYear < year || (currentYear === year && currentMonth < month))
return jsonError("Cannot get events for a time in the future", 400);
const eventRecords = await context.env.D1.prepare(
"SELECT answer, approved, created_by, day, details, month, pending, performed_at, type, year FROM events WHERE month = ? AND year = ? ORDER BY day ASC;",
)
.bind(month, year)
.all();
const eventRecords = await context.data.prisma.event.findMany({
select: {
answer: true,
approved: true,
created_by: true,
day: true,
details: true,
month: true,
pending: true,
performed_at: true,
type: true,
year: true,
},
where: {
month: month,
year: year,
},
orderBy: {
day: "asc",
},
});
if (!eventRecords.success) return jsonError("Failed to retrieve events", 400);
return jsonResponse(JSON.stringify(eventRecords.results));
return jsonResponse(JSON.stringify(eventRecords));
}

View File

@@ -7,19 +7,25 @@ export async function onRequestPost(context: RequestContext) {
if (statsReduction && typeof statsReduction !== "number")
return jsonError("Invalid stat reduction", 400);
const appeal: Record<string, any> | null = await context.env.D1.prepare(
"SELECT * FROM game_appeals WHERE id = ?;",
)
.bind(context.params.id)
.first();
const appeal = await context.data.prisma.gameAppeal.findUnique({
select: {
roblox_id: true,
type: true,
},
where: {
id: context.params.id as string,
},
});
if (!appeal) return jsonError("Appeal not found", 400);
const { etag, value: banList } = await getBanList(context);
await context.env.D1.prepare("DELETE FROM game_appeals WHERE id = ?;")
.bind(context.params.id)
.run();
await context.data.prisma.gameAppeal.delete({
where: {
id: context.params.id as string,
},
});
if (!banList[appeal.roblox_id]?.BanType)
return new Response(null, {
@@ -46,18 +52,15 @@ export async function onRequestPost(context: RequestContext) {
};
}
await context.env.D1.prepare(
"INSERT INTO game_mod_logs (action, evidence, executed_at, executor, id, target) VALUES (?, ?, ?, ?, ?, ?);",
)
.bind(
`accept appeal | ${banList[appeal.roblox_id]?.BanType === 2 ? "ban" : appeal.type}`,
`https://carcrushers.cc/mod-queue?id=${context.params.id}&type=gma`,
Date.now(),
context.data.current_user.id,
crypto.randomUUID(),
appeal.roblox_id,
)
.run();
await context.data.prisma.gameModLog.create({
data: {
action: `accept appeal | ${banList[appeal.roblox_id]?.BanType === 2 ? "ban" : appeal.type}`,
evidence: `https://carcrushers.cc/mod-queue?id=${context.params.id}&type=gma`,
executor: context.data.current_user.id,
id: crypto.randomUUID(),
target: appeal.roblox_id,
},
});
await setBanList(context, banList, etag);

View File

@@ -2,18 +2,22 @@ import { jsonError } from "../../../common.js";
export async function onRequestPost(context: RequestContext) {
const appealId = context.params.id as string;
const appeal = await context.env.D1.prepare(
"SELECT * FROM game_appeals WHERE id = ?;",
)
.bind(appealId)
.first();
const appeal = await context.data.prisma.gameAppeal.findUnique({
select: {
roblox_id: true,
},
where: {
id: appealId,
},
});
if (!appeal) return jsonError("Appeal not found", 404);
await context.env.D1.prepare("DELETE FROM game_appeals WHERE id = ?;")
.bind(appealId)
.run();
await context.data.prisma.gameAppeal.delete({
where: {
id: appealId,
},
});
await context.env.DATA.put(
`gameappealblock_${appeal.roblox_id}`,

View File

@@ -10,11 +10,14 @@ export default async function (
types?: string[];
}> {
if (
await context.env.D1.prepare(
"SELECT * FROM game_appeals WHERE roblox_id = ?;",
)
.bind(user)
.first()
await context.data.prisma.gameAppeal.findFirst({
select: {
id: true,
},
where: {
roblox_id: user,
},
})
)
return {
can_appeal: false,
@@ -47,22 +50,20 @@ export default async function (
).toLocaleString()} to submit another appeal`,
};
const userLogs = await context.env.D1.prepare(
"SELECT action, executed_at FROM game_mod_logs WHERE target = ? ORDER BY executed_at DESC;",
)
.bind(user)
.all();
if (userLogs.error)
return {
error: "Could not determine your eligibility",
};
const userLogs = await context.data.prisma.gameModLog.findMany({
select: {
action: true,
executed_at: true,
},
where: {
target: user,
},
});
// Legacy bans
if (!userLogs.results.length)
return { can_appeal: true, reason: "", types: ["ban"] };
if (!userLogs.length) return { can_appeal: true, reason: "", types: ["ban"] };
const allowedTime = (userLogs.results[0].executed_at as number) + 2592000000;
const allowedTime = new Date(userLogs[0].executed_at).getTime() + 2592000000;
if (Date.now() < allowedTime)
return {
@@ -72,11 +73,7 @@ export default async function (
).toLocaleString()} to submit an appeal`,
};
if (
userLogs.results.find((r: Record<string, any>) =>
r.action.startsWith("accept appeal"),
)
)
if (userLogs.find((r) => r.action.startsWith("accept appeal")))
return {
can_appeal: false,
reason: "We do not accept appeals from repeat offenders",

View File

@@ -52,19 +52,16 @@ export async function onRequestPost(context: RequestContext) {
context.request.headers.get("cf-ray")?.split("-")[0]
}${Date.now()}`;
await context.env.D1.prepare(
"INSERT INTO game_appeals (created_at, id, reason_for_unban, roblox_id, roblox_username, type, what_happened) VALUES (?, ?, ?, ?, ?, ?, ?);",
)
.bind(
Date.now(),
appealId,
reasonForUnban,
id,
username,
await context.data.prisma.gameAppeal.create({
data: {
id: appealId,
reason_for_unban: reasonForUnban,
roblox_id: id,
roblox_username: username,
type,
whatHappened,
)
.run();
what_happened: whatHappened,
},
});
await fetch(context.env.REPORTS_WEBHOOK, {
body: JSON.stringify({

View File

@@ -58,13 +58,14 @@ export async function onRequestGet(context: RequestContext) {
} else if (banData.BanType === 2) current_status = "Banned";
const response = {
history: (
await context.env.D1.prepare(
"SELECT * FROM game_mod_logs WHERE target = ? ORDER BY executed_at DESC;",
)
.bind(users[0].id)
.all()
).results,
history: await context.data.prisma.gameModLog.findMany({
orderBy: {
executed_at: "desc",
},
where: {
target: users[0].id,
},
}),
user: {
avatar: thumbnailRequest.ok
? (

View File

@@ -18,18 +18,15 @@ export async function onRequestPost(context: RequestContext) {
if (isNaN(parseInt(user))) return jsonError("Invalid user ID", 400);
await context.env.D1.prepare(
"INSERT INTO game_mod_logs (action, evidence, executed_at, executor, id, target) VALUES (?, ?, ?, ?, ?, ?);",
)
.bind(
"revoke",
ticket_link,
Date.now(),
context.data.current_user.id,
crypto.randomUUID(),
parseInt(user),
)
.run();
await context.data.prisma.gameModLog.create({
data: {
action: "revoke",
evidence: ticket_link,
executor: context.data.current_user.id,
id: crypto.randomUUID(),
target: parseInt(user),
},
});
const { etag, value: banList } = await getBanList(context);

View File

@@ -2,38 +2,50 @@ import { jsonError, jsonResponse } from "../../../common.js";
export async function onRequestDelete(context: RequestContext) {
const noteId = context.params.id as string;
const creatorIdResult: null | Record<string, string> =
await context.env.D1.prepare(
"SELECT created_by FROM game_mod_logs WHERE id = ?;",
)
.bind(noteId)
.first();
const creatorIdResult = await context.data.prisma.gameModNote.findUnique({
select: {
created_by: true,
},
where: {
id: noteId,
},
});
if (creatorIdResult?.created_by !== context.data.current_user.id)
try {
await context.data.prisma.gameModNote.delete({
select: {
id: true,
},
where: {
created_by: context.data.current_user.id,
id: noteId,
},
});
} catch {
return jsonError("Cannot delete notes that are not your own", 403);
await context.env.D1.prepare("DELETE FROM game_mod_logs WHERE id = ?;")
.bind(noteId)
.first();
}
return new Response(null, { status: 204 });
}
export async function onRequestGet(context: RequestContext) {
const noteId = context.params.id as string;
const result = await context.env.D1.prepare(
"SELECT * FROM game_mod_notes WHERE id = ?;",
)
.bind(noteId)
.first();
const result = await context.data.prisma.gameModNote.findUnique({
where: {
id: noteId,
},
});
if (!result) return jsonError("Note not found", 404);
const noteData = structuredClone(result);
let noteData = structuredClone(result);
const gmeEntry: null | { time: number; user: string; name: string } =
await context.env.DATA.get(`gamemod_${result.created_by}`, "json");
if (gmeEntry) noteData.creator_name = gmeEntry.name;
if (gmeEntry)
noteData = Object.defineProperty(noteData, "creator_name", {
value: gmeEntry.name,
});
return jsonResponse(JSON.stringify(noteData));
}

View File

@@ -1,18 +1,22 @@
import { jsonError, jsonResponse } from "../../common.js";
import sendEmail from "../../email.js";
import { sendPushNotification } from "../../gcloud.js";
import { type JsonArray, type JsonObject } from "@prisma/client/runtime/client";
export async function onRequestDelete(context: RequestContext) {
const result = await context.env.D1.prepare(
"SELECT json_extract(user, '*.id') AS uid FROM inactivity_notices WHERE id = ?;",
)
.bind(context.params.id)
.first();
const result = await context.data.prisma.inactivityNotice.findUnique({
select: {
user: true,
},
where: {
id: context.params.id as string,
},
});
if (!result) return jsonError("No inactivity notice with that ID", 404);
if (
result.uid !== context.data.current_user.id &&
(result.user as JsonObject).id !== context.data.current_user.id &&
!(context.data.current_user.permissions & (1 << 0))
)
return jsonError(
@@ -39,26 +43,17 @@ export async function onRequestGet(context: RequestContext) {
)
return jsonError("Forbidden", 403);
const result: Record<
string,
string | number | { [k: string]: string }
> | null = await context.env.D1.prepare(
"SELECT * FROM inactivity_notices WHERE id = ?;",
)
.bind(context.params.id)
.first();
if (!result) return jsonError("Inactivity notice does not exist", 404);
result.decisions = JSON.parse(result.decisions as string);
result.departments = JSON.parse(result.departments as string);
result.user = JSON.parse(result.user as string);
const result = await context.data.prisma.inactivityNotice.findUnique({
where: {
id: context.params.id as string,
},
});
return jsonResponse(JSON.stringify(result));
}
export async function onRequestPost(context: RequestContext) {
const { accepted }: { accepted?: boolean } = context.data.body;
const { accepted }: { accepted?: any } = context.data.body;
if (typeof accepted !== "boolean")
return jsonError("'accepted' must be a boolean", 400);
@@ -77,32 +72,45 @@ export async function onRequestPost(context: RequestContext) {
if (!userAdminDepartments.length)
return jsonError("You are not a manager of any departments", 403);
const requestedNotice: { [k: string]: any } | null =
await context.env.D1.prepare(
"SELECT decisions, departments, user FROM inactivity_notices WHERE id = ?;",
)
.bind(context.params.id)
.first();
const requestedNotice = await context.data.prisma.inactivityNotice.findUnique(
{
select: {
decisions: true,
departments: true,
user: true,
},
where: {
id: context.params.id as string,
},
},
);
if (!requestedNotice)
return jsonError("Inactivity notices does not exist", 404);
const decisions: { [dept: string]: boolean } = JSON.parse(
requestedNotice.decisions,
);
const decisions = requestedNotice.decisions as { [k: string]: boolean };
for (const department of userAdminDepartments) {
if (!JSON.parse(requestedNotice.departments).includes(department)) continue;
if (!(requestedNotice.departments as JsonArray).includes(department))
continue;
decisions[department] = accepted;
}
const applicableDepartments = JSON.parse(requestedNotice.departments).length;
const applicableDepartments = (requestedNotice.departments as JsonArray)
.length;
const user = requestedNotice.user as JsonObject;
await context.env.D1.prepare(
"UPDATE inactivity_notices SET decisions = ?, user = json_remove(user, '$.email') WHERE id = ?;",
)
.bind(JSON.stringify(decisions), context.params.id)
.run();
delete user.email;
await context.data.prisma.inactivityNotice.update({
data: {
decisions,
user,
},
where: {
id: context.params.id as string,
},
});
if (Object.values(decisions).length === applicableDepartments) {
const approved =
@@ -111,11 +119,16 @@ export async function onRequestPost(context: RequestContext) {
const denied =
Object.values(decisions).filter((d) => !d).length !==
applicableDepartments;
const fcmTokenResult: FCMTokenResult | null = await context.env.D1.prepare(
"SELECT token FROM push_notifications WHERE event_id = ? AND event_type = 'inactivity';",
)
.bind(context.params.id)
.first();
const fcmTokenResult =
await context.data.prisma.pushNotification.findUnique({
select: {
token: true,
},
where: {
event_id: context.params.id as string,
event_type: "inactivity",
},
});
if (fcmTokenResult) {
let status = "Approved";
@@ -132,16 +145,19 @@ export async function onRequestPost(context: RequestContext) {
fcmTokenResult.token,
);
await context.env.D1.prepare(
"DELETE FROM push_notifications WHERE event_id = ? AND event_type = 'inactivity';",
).bind(context.params.id);
await context.data.prisma.pushNotification.delete({
where: {
event_id: context.params.id as string,
event_type: "inactivity",
},
});
} else {
await sendEmail(
requestedNotice.user.email,
(requestedNotice.user as JsonObject).email as string,
context.env.MAILGUN_API_KEY,
`Inactivity Request ${approved ? "Approved" : "Denied"}`,
`inactivity_${approved ? "approved" : "denied"}`,
{ username: requestedNotice.user.username },
{ username: (requestedNotice.user as JsonObject).username as string },
);
}
}

View File

@@ -20,31 +20,31 @@ export async function onRequestPost(context: RequestContext) {
(context.request.headers.get("cf-ray") as string).split("-")[0] +
Date.now().toString();
await context.env.D1.prepare(
"INSERT INTO inactivity_notices (created_at, departments, end, hiatus, id, reason, start, user) VALUES (?, ?, ?, ?, ?, ?, ?, ?);",
)
.bind(
Date.now(),
JSON.stringify(departments),
await context.data.prisma.inactivityNotice.create({
data: {
decisions: {},
departments,
end,
typeof hiatus === "boolean" ? Number(hiatus) : 0,
inactivityId,
hiatus,
id: inactivityId,
reason,
start,
JSON.stringify({
user: {
id: context.data.current_user.id,
email: context.data.current_user.email,
username: context.data.current_user.username,
}),
)
.run();
},
},
});
if (typeof senderTokenId === "string") {
await context.env.D1.prepare(
"INSERT INTO push_notifications (created_at, event_id, event_type) VALUES (?, ?, ?);",
)
.bind(Date.now(), inactivityId, "inactivity")
.run();
await context.data.prisma.pushNotification.create({
data: {
event_id: inactivityId,
event_type: "inactivity",
token: senderTokenId,
},
});
}
const departmentsToNotify = [];

View File

@@ -1,19 +1,22 @@
import { jsonError, jsonResponse } from "../../common.js";
import { jsonResponse } from "../../common.js";
export async function onRequestGet(context: RequestContext) {
const {
results,
success,
}: {
results: { id: string }[];
success: boolean;
} = await context.env.D1.prepare(
"SELECT created_at, id, open, target_usernames FROM reports WHERE json_extract(user, '$.id') = ? ORDER BY created_at LIMIT 50;",
)
.bind(context.data.current_user.id)
.all();
if (!success) return jsonError("Failed to retrieve reports", 500);
return jsonResponse(JSON.stringify(results));
return jsonResponse(
JSON.stringify(
await context.data.prisma.report.findMany({
select: {
created_at: true,
id: true,
open: true,
target_usernames: true,
},
where: {
user: {
path: "id",
equals: context.data.current_user.id,
},
},
}),
),
);
}

View File

@@ -17,11 +17,10 @@ export async function onRequestPost(context: RequestContext) {
await context.env.DATA.delete(`reportprocessing_${id}`);
const value = await context.env.D1.prepare(
"SELECT id FROM reports WHERE id = ?;",
)
.bind(id)
.first();
const value = await context.data.prisma.report.findUnique({
select: { id: true },
where: { id },
});
if (!value) return jsonError("Report is missing", 500);

View File

@@ -15,26 +15,27 @@ export async function onRequestPost(context: RequestContext) {
)
return jsonError("No processing report with that ID found", 404);
const data: Record<string, any> | null = await context.env.D1.prepare(
"SELECT attachments FROM reports WHERE id = ?;",
)
.bind(id)
.first();
const data = await context.data.prisma.report.findUnique({
select: {
attachments: true,
},
where: {
id,
},
});
if (!data) return jsonError("No report with that ID found", 404);
data.attachments = JSON.parse(data.attachments);
const accessToken = await GetAccessToken(context.env);
const attachmentDeletePromises = [];
const existingAttachments = [...data.attachments];
const existingAttachments = [...(data.attachments as string[])];
for (const attachment of existingAttachments) {
if (!attachment.startsWith("t/")) data.attachments.push(`t/${attachment}`);
else data.attachments.push(attachment.replace("t/", ""));
for (let i = 0; i < existingAttachments.length; i++) {
if (!existingAttachments[i].startsWith("t/"))
existingAttachments[i] = existingAttachments[i].replace("t/", "");
}
for (const attachment of data.attachments)
for (const attachment of existingAttachments)
attachmentDeletePromises.push(
fetch(
`https://storage.googleapis.com/storage/v1/b/portal-carcrushers-cc/o/${encodeURIComponent(
@@ -50,9 +51,11 @@ export async function onRequestPost(context: RequestContext) {
);
await Promise.allSettled(attachmentDeletePromises);
await context.env.D1.prepare("DELETE FROM reports WHERE id = ?;")
.bind(id)
.run();
await context.data.prisma.report.delete({
where: {
id,
},
});
return new Response(null, {
status: 204,

View File

@@ -1,11 +1,18 @@
import { jsonResponse } from "../../common.js";
export async function onRequestGet(context: RequestContext) {
const { results } = await context.env.D1.prepare(
"SELECT created_at, destination, path FROM short_links WHERE user = ?;",
)
.bind(context.data.current_user.id)
.all();
return jsonResponse(JSON.stringify(results));
return jsonResponse(
JSON.stringify(
await context.data.prisma.shortLink.findMany({
select: {
created_at: true,
destination: true,
path: true,
},
where: {
user: context.data.current_user.id,
},
}),
),
);
}

View File

@@ -6,11 +6,14 @@ export async function onRequestPost(context: RequestContext) {
if (typeof path !== "string" || path.length > 256)
return jsonError("Invalid path", 400);
const result = await context.env.D1.prepare(
"SELECT path FROM short_links WHERE path = ?;",
)
.bind(path)
.first();
const result = await context.data.prisma.shortLink.findUnique({
select: {
path: true,
},
where: {
path,
},
});
if (result)
return jsonError(
@@ -78,11 +81,13 @@ export async function onRequestPost(context: RequestContext) {
400,
);
await context.env.D1.prepare(
"INSERT INTO short_links (created_at, destination, path, user) VALUES (?, ?, ?, ?);",
)
.bind(Date.now(), destination, path, context.data.current_user.id)
.run();
await context.data.prisma.shortLink.create({
data: {
destination,
path,
user: context.data.current_user.id,
},
});
return new Response(null, {
status: 204,

View File

@@ -149,7 +149,7 @@ model Report {
model ShortLink {
created_at DateTime @default(now())
destination String
path String @unique
path String @id @unique
user String
@@map("short_links")