Code cleanup

This commit is contained in:
Dominic Ferrando
2026-10-03 23:49:16 -04:00
parent 7afde2c323
commit 9bf60b7c8b
8 changed files with 112 additions and 66 deletions
+55 -58
View File
@@ -5,14 +5,14 @@ import {
Activity,
} from "@blade-and-brawn/domain"
import { cors } from "@elysiajs/cors";
import { Elysia, redirect, status, t } from "elysia";
import { Elysia, NotFoundError, redirect, status, t } from "elysia";
import {
PrintfulError,
WebflowError,
Printful,
Webflow,
} from "@blade-and-brawn/commerce";
import { AccountIdSchema, BigIntIdSchema, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, log } from "./util";
import { AccountIdSchema, BadGatewayError, BadRequestError, BigIntIdSchema, ConflictError, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, ForbiddenError, HttpError, log, UnauthorizedError } from "./util";
import serverTiming from "@elysia/server-timing";
import jwt from "@elysia/jwt";
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
@@ -33,6 +33,7 @@ import { VerificationsService, VerificationStatusSchema } from "./services/verif
const EVENT_QUEUE_MANAGE_DELAY_MS = 1000 // 1 sec
const JWT_EXP = "1d";
const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for cookie maxAge
const PG_UNIQUE_VIOLATION = "23505";
// SERVICES
// -----------------------
@@ -117,35 +118,31 @@ export const app = new Elysia()
})
.use(authPlugin)
.error({
PrintfulError,
WebflowError,
CalculatorUnavailableError
})
.error({ PrintfulError, WebflowError, CalculatorUnavailableError, HttpError })
.onError(({ code, error }) => {
// Database Errors
if (error instanceof DatabaseError && error.code === "23505")
return status(409, { error: "Conflicts with an existing record" });
// Database errors
if (error instanceof DatabaseError) {
if (error.code === PG_UNIQUE_VIOLATION)
return status(409, { error: "Conflicts with an existing record" });
log.error({ err: error }, "Database error");
return status(500, { error: "Internal Server Error" });
}
// Custom Errors
// All other errors
switch (code) {
case "HttpError":
break;
case "PrintfulError":
case "WebflowError":
log.error(
{ upstreamStatus: error.upstreamStatus, payload: error.payload },
error.message,
);
return status(502, { error: error.message });
case "CalculatorUnavailableError":
log.error({ err: error.cause }, error.message);
return status(503, { error: error.message });
log.error({ upstreamStatus: error.upstreamStatus, payload: error.payload }, error.message);
break;
case "NOT_FOUND":
return status(404, { error: error.message || "NOT_FOUND" });
case "VALIDATION":
return status(422, { error: error.message });
return status(422, { error: error.message, detail: error.detail });
default:
log.error({ err: error }, "unhandled error");
log.error({ err: error }, "Unhandled error");
return status(500, { error: "Internal Server Error" })
}
})
@@ -171,7 +168,7 @@ export const app = new Elysia()
.post("/auth/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
const account = await s.Accounts.getByEmail(email);
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
if (!account || !password_match) return status(401, { error: "Invalid credentials" });
if (!account || !password_match) throw new UnauthorizedError("Invalid credentials");
auth.set({
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
@@ -209,10 +206,10 @@ export const app = new Elysia()
return redirect(url.toString(), 302);
})
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
if (query.error) return status(400, { error: query.error_description ? `${query.error}: ${query.error_description}` : query.error });
if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error);
if (!query.state) return status(400, { error: "No Discord OAuth2 state query parameter provided" });
if (query.state !== authDiscord.value) return status(400, { error: "Invalid Discord OAuth state" });
if (!query.state) throw new BadRequestError("No Discord OAuth2 state query parameter provided");
if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state");
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
@@ -229,7 +226,7 @@ export const app = new Elysia()
});
if (!tokenRes.ok) {
const errorBody = await tokenRes.json().catch(() => null);
return status(502, { error: errorBody ?? "Discord token exchange failed" });
throw new BadGatewayError(errorBody ?? "Discord token exchange failed");
}
const tokenResPayload = await tokenRes.json();
@@ -240,7 +237,7 @@ export const app = new Elysia()
});
if (!identityRes.ok) {
const errorBody = await identityRes.json().catch(() => null);
return status(502, { error: errorBody ?? "Failed to fetch Discord identity" });
throw new BadGatewayError(errorBody ?? "Failed to fetch Discord identity");
}
const identityResPayload = await identityRes.json();
@@ -368,7 +365,7 @@ export const app = new Elysia()
// Sync status
.get("/", async ({ sessionId }) => {
const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(sessionId);
if (!latestSyncState) return status(404, { error: "No product sync found for the provided session" });
if (!latestSyncState) throw new NotFoundError("No product sync found for the provided session");
return latestSyncState;
})
// Run sync
@@ -387,10 +384,10 @@ export const app = new Elysia()
)
.get("/:pProductId", async ({ params: { pProductId } }) => {
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
if (!pProduct) return status(404, { error: "Missing printful product" });
if (!pProduct) throw new NotFoundError("Missing printful product");
const wProductId = pProduct.sync_product.external_id.split("-")[0];
if (!wProductId) return status(404, { error: "Missing webflow product ID" });
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
@@ -423,7 +420,7 @@ export const app = new Elysia()
})
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
if (!wOrder) return status(404, { error: "Missing webflow order" });
if (!wOrder) throw new NotFoundError("Missing webflow order");
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
@@ -431,10 +428,10 @@ export const app = new Elysia()
}, { params: t.Object({ wOrderId: t.String() }) })
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
if (!wOrder) return status(404, { error: "Missing webflow order" });
if (!wOrder) throw new NotFoundError("Missing webflow order");
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
if (pOrder) return status(409, { error: "Cannot sync an already synced webflow order" });
if (pOrder) throw new ConflictError("Cannot sync an already synced webflow order");
await s.Commerce.Apparel.Orders.Queue.enqueue({
type: "apparel_order_create",
@@ -466,14 +463,14 @@ export const app = new Elysia()
})
.get("/:id", async ({ params: { id } }) => {
const event = await s.Events.get(id);
if (!event) return status(404, { error: "Event not found" });
if (!event) throw new NotFoundError("Event not found");
return { ...event, status: EventsService.status(event) };
}, {
params: t.Object({ id: BigIntIdSchema })
})
.post("/:id/retry", async ({ params: { id } }) => {
const retried = await s.Events.retry(id);
if (!retried) return status(404, { error: "Event not found or not in a failed state" });
if (!retried) throw new NotFoundError("Event not found or not in a failed state");
}, {
params: t.Object({ id: BigIntIdSchema })
})
@@ -485,7 +482,7 @@ export const app = new Elysia()
// TODO: for added security, could enforce bot or admin only access
.get("/:id/stats", async ({ params: { id } }) => {
const stats = await s.Accounts.stats(id);
if (!stats) return status(404, { error: "Account stats not found" });
if (!stats) throw new NotFoundError("Account stats not found");
return stats;
}, {
params: t.Object({ id: AccountIdSchema })
@@ -508,7 +505,7 @@ export const app = new Elysia()
.guard({ authAdmin: true }, (app) => app
.get("/:id", async ({ params: { id } }) => {
const account = await s.Accounts.get(id);
if (!account) return status(404, { error: "Account not found" });
if (!account) throw new NotFoundError("Account not found");
return account;
}, {
params: t.Object({ id: AccountIdSchema })
@@ -517,7 +514,7 @@ export const app = new Elysia()
.group("/me", { auth: true }, (app) => app
.get("/stats", async ({ accountId }) => {
const stats = await s.Accounts.stats(accountId);
if (!stats) return status(404, { error: "Account stats not found" });
if (!stats) throw new NotFoundError("Account stats not found");
return stats;
})
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
@@ -534,7 +531,7 @@ export const app = new Elysia()
})
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
const deleted = await s.Assessments.delete(id, accountId);
if (!deleted) return status(404, { error: "Assessment not found" });
if (!deleted) throw new NotFoundError("Assessment not found");
}, {
params: t.Object({ id: BigIntIdSchema })
})
@@ -553,12 +550,12 @@ export const app = new Elysia()
})
.post("/verifications", async ({ body: { assessmentId }, accountId }) => {
const assessment = await s.Assessments.get(assessmentId, accountId);
if (!assessment) return status(404, { error: "Assessment not found" });
if (!assessment) throw new NotFoundError("Assessment not found");
// TODO: only allow a single active non-completed verification at a time
const created = await s.Verifications.create(assessmentId);
if (!created) return status(409, { error: "This assessment already has a verification" });
if (!created) throw new ConflictError("This assessment already has a verification");
return { ...created, uploadUrls: presignVerificationUploads(assessmentId) };
}, {
@@ -568,10 +565,10 @@ export const app = new Elysia()
})
.post("/verifications/:id/reopen", async ({ params: { id }, accountId }) => {
const verification = await s.Verifications.get(id, accountId);
if (!verification) return status(404, { error: "Verification not found" });
if (!verification) throw new NotFoundError("Verification not found");
const reopened = await s.Verifications.reopen(id);
if (!reopened) return status(409, { error: `Cannot reopen a ${verification.status} verification` });
if (!reopened) throw new ConflictError(`Cannot reopen a ${verification.status} verification`);
return { ...reopened, uploadUrls: presignVerificationUploads(verification.assessment_id) };
}, {
@@ -579,11 +576,11 @@ export const app = new Elysia()
})
.post("/verifications/:id/submit", async ({ params: { id }, accountId }) => {
const verification = await s.Verifications.get(id, accountId);
if (!verification) return status(404, { error: "Verification not found" });
if (!verification) throw new NotFoundError("Verification not found");
if (verification.status === "draft") {
const { contents } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/`, maxKeys: 1 });
if (!contents?.length) return status(409, { error: "No media uploaded" });
if (!contents?.length) throw new ConflictError("No media uploaded");
}
const submitted = await s.Verifications.submit(id);
@@ -593,9 +590,9 @@ export const app = new Elysia()
}
const current = await s.Verifications.get(id, accountId);
if (!current) return status(404, { error: "Verification not found" });
if (!current) throw new NotFoundError("Verification not found");
if (current.status === "submitted") return { id: current.id, status: current.status };
return status(409, { error: `Cannot submit a ${current.status} verification` });
throw new ConflictError(`Cannot submit a ${current.status} verification`);
}, {
params: t.Object({ id: BigIntIdSchema })
})
@@ -615,7 +612,7 @@ export const app = new Elysia()
})
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
const updated = await s.Assessments.update(id, player, activityPerformances);
if (!updated) return status(404, { error: "Assessment not found" });
if (!updated) throw new NotFoundError("Assessment not found");
return updated;
}, {
params: t.Object({ id: BigIntIdSchema }),
@@ -645,7 +642,7 @@ export const app = new Elysia()
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth
.get("/:id", async ({ params: { id } }) => {
const verification = await s.Verifications.get(id);
if (!verification) return status(404, { error: "Verification not found" });
if (!verification) throw new NotFoundError("Verification not found");
const { contents = [] } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/` });
const media = contents.map(({ key, size, lastModified }) => ({
@@ -665,8 +662,8 @@ export const app = new Elysia()
if (updated) return updated;
const verification = await s.Verifications.get(id);
if (!verification) return status(404, { error: "Verification not found" });
return status(409, { error: `Cannot request action on a ${verification.status} verification` });
if (!verification) throw new NotFoundError("Verification not found");
throw new ConflictError(`Cannot request action on a ${verification.status} verification`);
}, {
params: t.Object({ id: BigIntIdSchema }),
body: t.Object({
@@ -679,14 +676,14 @@ export const app = new Elysia()
const portalSession = auth.value && await jwt.verify(auth.value);
const completerId = completedBy ?? (portalSession ? portalSession.accountId?.toString() : undefined);
const completer = completerId && await s.Accounts.get(completerId);
if (!completer || completer.role !== "admin") return status(403, { error: "Only a classmaster can complete a verification" });
if (!completer || completer.role !== "admin") throw new ForbiddenError("Only a classmaster can complete a verification");
const updated = await s.Verifications.complete(id, completer.id, activityVerifications);
if (updated) return updated;
const verification = await s.Verifications.get(id);
if (!verification) return status(404, { error: "Verification not found" });
return status(409, { error: `Cannot complete a ${verification.status} verification` });
if (!verification) throw new NotFoundError("Verification not found");
throw new ConflictError(`Cannot complete a ${verification.status} verification`);
}, {
params: t.Object({ id: BigIntIdSchema }),
body: t.Object({
@@ -700,7 +697,7 @@ export const app = new Elysia()
.post("/webhooks/printful", async ({ body, query }) => {
// https://webflow.com/integrations/printful
if (!s.Commerce.Printful.Util.verifySecret(query.secret))
return status(400, { error: "Invalid secret" });
throw new BadRequestError("Invalid secret");
const payload = body as Printful.Webhook.EventPayload;
@@ -723,7 +720,7 @@ export const app = new Elysia()
const pProduct = payload.data.sync_product;
const wProductId = pProduct.external_id.split("-")[0];
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
if (!wProductId) return status(404, { error: "Missing webflow product ID" });
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
await s.Commerce.Apparel.Syncs.Queue.enqueue({
type: "apparel_sync_delete",
@@ -755,7 +752,7 @@ export const app = new Elysia()
}, { query: t.Object({ secret: t.String() }) })
.post("/webhooks/webflow", async ({ request, body }) => {
if (!s.Commerce.Webflow.Util.verifySecret(request, body))
return status(400, { error: "Invalid signature" });
throw new BadRequestError("Invalid signature");
const payload = body as Webflow.Webhook.EventPayload;