Greatly reduce repeated code

This commit is contained in:
2023-10-19 16:50:48 -04:00
parent 47e639be43
commit dd2d9f2672
34 changed files with 196 additions and 481 deletions

View File

@ -1,4 +1,5 @@
import { GenerateUploadURL } from "../../gcloud.js";
import { jsonError } from "../../common.js";
const allowedFileTypes = [
"image/gif",
@ -17,36 +18,21 @@ export async function onRequestPost(context: RequestContext) {
(p) => context.data.current_user.permissions & p,
)
)
return new Response('{"error":"Forbidden"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
return jsonError("Forbidden", 403);
if (
context.request.headers
.get("content-type")
?.startsWith("multipart/form-data; boundary=")
)
return new Response('{"error":"Invalid content type"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid content type", 400);
let body: FormData;
try {
body = await context.request.formData();
} catch {
return new Response('{"error":"Invalid form data"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid form data", 400);
}
if (
@ -59,39 +45,21 @@ export async function onRequestPost(context: RequestContext) {
"ban_unappealable",
].includes(body.get("punishment") as string)
)
return new Response('{"error":"Invalid punishment"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid punishment", 400);
if (!(body.get("user") as string).match(/^\d{17,19}$/))
return new Response('{"error":"Invalid user"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid user", 400);
// @ts-expect-error
const files: File[] = body.keys().find((key) => key.match(/^files\[\d]$/));
const urlPromises = [];
const origin = context.request.headers.get("Origin");
if (!origin)
return new Response('{"error":"Origin header missing"}', {
status: 400,
});
if (!origin) return jsonError("Origin header missing", 400);
for (const file of files) {
if (!allowedFileTypes.includes(file.type))
return new Response(`{"error":"File ${file.name} is not valid"}`, {
headers: {
"content-type": "application/json",
},
status: 415,
});
return jsonError(`File ${file.name} is not valid`, 415);
const attachmentKey = `${Date.now()}${Math.round(
Math.random() * 10000000,
@ -111,12 +79,7 @@ export async function onRequestPost(context: RequestContext) {
const settledURLPromises = await Promise.allSettled(urlPromises);
if (settledURLPromises.find((p) => p.status === "rejected"))
return new Response('{"error":"Failed to process one or more files"}', {
headers: {
"content-type": "application/json",
},
status: 500,
});
return jsonError("Failed to process one or more files", 500);
const infractionId = `${body.get(
"user",