Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Use direct uploads for infraction (files are processed serverside)
  • Loading branch information
regalijan committed Nov 2, 2023
1 parent 6f2bb0e commit fe024c3
Showing 1 changed file with 16 additions and 23 deletions.
39 changes: 16 additions & 23 deletions functions/api/infractions/new.ts
@@ -1,4 +1,4 @@
import { GenerateUploadURL } from "../../gcloud.js";
import { GetAccessToken } from "../../gcloud.js";
import { jsonError } from "../../common.js";

const allowedFileTypes = [
Expand Down Expand Up @@ -69,11 +69,13 @@ export async function onRequestPost(context: RequestContext) {
files.push(file);
}

const urlPromises = [];
const uploadPromises = [];
const origin = context.request.headers.get("Origin");

if (!origin) return jsonError("Origin header missing", 400);

const accessToken = await GetAccessToken(context.env);

for (const file of files) {
if (!allowedFileTypes.includes(file.type))
return jsonError(`File ${file.name} is not valid`, 415);
Expand All @@ -82,35 +84,26 @@ export async function onRequestPost(context: RequestContext) {
Math.random() * 10000000,
).toString()}/${file.name}`;

urlPromises.push(
GenerateUploadURL(
context.env,
attachmentKey,
file.size,
(allowedFileTypes.find((t) => t === file.type) as string).split("/")[1],
origin,
uploadPromises.push(
fetch(
`https://storage.googleapis.com/upload/storage/v1/b/portal-carcrushers-cc/o?name=${encodeURIComponent(
attachmentKey,
)}&uploadType=media`,
{
headers: {
authorization: `Bearer ${accessToken}`,
"content-type": file.type,
},
},
),
);
}

const settledURLPromises = await Promise.allSettled(urlPromises);

if (settledURLPromises.find((p) => p.status === "rejected"))
return jsonError("Failed to process one or more files", 500);
await Promise.allSettled(uploadPromises);

const infractionId = `${body.get(
"user",
)}${Date.now()}${context.request.headers.get("cf-ray")?.split("-")[0]}`;
const uploadReqs = [];

for (let i = 0; i < files.length; i++) {
uploadReqs.push(
fetch(settledURLPromises[i] as unknown as string, {
body: files[i],
method: "PUT",
}),
);
}

await context.env.DATA.put(
infractionId,
Expand Down

0 comments on commit fe024c3

Please sign in to comment.