Code cleanup
This commit is contained in:
@@ -9,7 +9,7 @@ import type { AccountRole } from "../services/accounts";
|
|||||||
import { VerificationsService } from "../services/verifications";
|
import { VerificationsService } from "../services/verifications";
|
||||||
|
|
||||||
const DEFAULT_DISCORD_ID = "1325552430942916731";
|
const DEFAULT_DISCORD_ID = "1325552430942916731";
|
||||||
const FIXTURES_DIR = path.join(import.meta.dir, "fixtures");
|
const MEDIA_DIR = path.join(import.meta.dir, "test-verification-media");
|
||||||
const BUCKET = `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`;
|
const BUCKET = `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`;
|
||||||
|
|
||||||
const { values: args } = parseArgs({
|
const { values: args } = parseArgs({
|
||||||
@@ -68,12 +68,12 @@ async function seedTestAssessment(accountId: string): Promise<string> {
|
|||||||
return result.id;
|
return result.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function uploadFixtures(assessmentId: string) {
|
async function uploadMedia(assessmentId: string) {
|
||||||
const names = await readdir(FIXTURES_DIR).catch(() => []);
|
const names = await readdir(MEDIA_DIR).catch(() => []);
|
||||||
if (names.length === 0) log.warn({ dir: FIXTURES_DIR }, "no fixture media found, verification will have no media");
|
if (names.length === 0) log.warn({ dir: MEDIA_DIR }, "no fixture media found, verification will have no media");
|
||||||
|
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
const file = Bun.file(path.join(FIXTURES_DIR, name));
|
const file = Bun.file(path.join(MEDIA_DIR, name));
|
||||||
const key = `${assessmentId}/${crypto.randomUUID()}`;
|
const key = `${assessmentId}/${crypto.randomUUID()}`;
|
||||||
await r2.write(key, file, { type: file.type });
|
await r2.write(key, file, { type: file.type });
|
||||||
log.info({ key, name, size: file.size }, "uploaded fixture media");
|
log.info({ key, name, size: file.size }, "uploaded fixture media");
|
||||||
@@ -96,7 +96,7 @@ async function uploadFixtures(assessmentId: string) {
|
|||||||
const verification = await verifications.create(assessmentId);
|
const verification = await verifications.create(assessmentId);
|
||||||
if (!verification) throw new Error("Failed to create test verification");
|
if (!verification) throw new Error("Failed to create test verification");
|
||||||
|
|
||||||
await uploadFixtures(assessmentId);
|
await uploadMedia(assessmentId);
|
||||||
|
|
||||||
const submitted = await verifications.submit(verification.id);
|
const submitted = await verifications.submit(verification.id);
|
||||||
if (!submitted) throw new Error("Failed to submit test verification");
|
if (!submitted) throw new Error("Failed to submit test verification");
|
||||||
|
|||||||
BIN
Binary file not shown.
Binary file not shown.
+55
-58
@@ -5,14 +5,14 @@ import {
|
|||||||
Activity,
|
Activity,
|
||||||
} from "@blade-and-brawn/domain"
|
} from "@blade-and-brawn/domain"
|
||||||
import { cors } from "@elysiajs/cors";
|
import { cors } from "@elysiajs/cors";
|
||||||
import { Elysia, redirect, status, t } from "elysia";
|
import { Elysia, NotFoundError, redirect, status, t } from "elysia";
|
||||||
import {
|
import {
|
||||||
PrintfulError,
|
PrintfulError,
|
||||||
WebflowError,
|
WebflowError,
|
||||||
Printful,
|
Printful,
|
||||||
Webflow,
|
Webflow,
|
||||||
} from "@blade-and-brawn/commerce";
|
} 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 serverTiming from "@elysia/server-timing";
|
||||||
import jwt from "@elysia/jwt";
|
import jwt from "@elysia/jwt";
|
||||||
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
|
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 EVENT_QUEUE_MANAGE_DELAY_MS = 1000 // 1 sec
|
||||||
const JWT_EXP = "1d";
|
const JWT_EXP = "1d";
|
||||||
const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for cookie maxAge
|
const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for cookie maxAge
|
||||||
|
const PG_UNIQUE_VIOLATION = "23505";
|
||||||
|
|
||||||
// SERVICES
|
// SERVICES
|
||||||
// -----------------------
|
// -----------------------
|
||||||
@@ -117,35 +118,31 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.use(authPlugin)
|
.use(authPlugin)
|
||||||
|
|
||||||
.error({
|
.error({ PrintfulError, WebflowError, CalculatorUnavailableError, HttpError })
|
||||||
PrintfulError,
|
|
||||||
WebflowError,
|
|
||||||
CalculatorUnavailableError
|
|
||||||
})
|
|
||||||
|
|
||||||
.onError(({ code, error }) => {
|
.onError(({ code, error }) => {
|
||||||
// Database Errors
|
// Database errors
|
||||||
if (error instanceof DatabaseError && error.code === "23505")
|
if (error instanceof DatabaseError) {
|
||||||
return status(409, { error: "Conflicts with an existing record" });
|
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) {
|
switch (code) {
|
||||||
|
case "HttpError":
|
||||||
|
break;
|
||||||
case "PrintfulError":
|
case "PrintfulError":
|
||||||
case "WebflowError":
|
case "WebflowError":
|
||||||
log.error(
|
log.error({ upstreamStatus: error.upstreamStatus, payload: error.payload }, error.message);
|
||||||
{ upstreamStatus: error.upstreamStatus, payload: error.payload },
|
break;
|
||||||
error.message,
|
|
||||||
);
|
|
||||||
return status(502, { error: error.message });
|
|
||||||
case "CalculatorUnavailableError":
|
|
||||||
log.error({ err: error.cause }, error.message);
|
|
||||||
return status(503, { error: error.message });
|
|
||||||
case "NOT_FOUND":
|
case "NOT_FOUND":
|
||||||
return status(404, { error: error.message || "NOT_FOUND" });
|
return status(404, { error: error.message || "NOT_FOUND" });
|
||||||
case "VALIDATION":
|
case "VALIDATION":
|
||||||
return status(422, { error: error.message });
|
return status(422, { error: error.message, detail: error.detail });
|
||||||
default:
|
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 } }) => {
|
.post("/auth/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
||||||
const account = await s.Accounts.getByEmail(email);
|
const account = await s.Accounts.getByEmail(email);
|
||||||
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
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({
|
auth.set({
|
||||||
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
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);
|
return redirect(url.toString(), 302);
|
||||||
})
|
})
|
||||||
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
.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) throw new BadRequestError("No Discord OAuth2 state query parameter provided");
|
||||||
if (query.state !== authDiscord.value) return status(400, { error: "Invalid Discord OAuth state" });
|
if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state");
|
||||||
|
|
||||||
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -229,7 +226,7 @@ export const app = new Elysia()
|
|||||||
});
|
});
|
||||||
if (!tokenRes.ok) {
|
if (!tokenRes.ok) {
|
||||||
const errorBody = await tokenRes.json().catch(() => null);
|
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();
|
const tokenResPayload = await tokenRes.json();
|
||||||
@@ -240,7 +237,7 @@ export const app = new Elysia()
|
|||||||
});
|
});
|
||||||
if (!identityRes.ok) {
|
if (!identityRes.ok) {
|
||||||
const errorBody = await identityRes.json().catch(() => null);
|
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();
|
const identityResPayload = await identityRes.json();
|
||||||
@@ -368,7 +365,7 @@ export const app = new Elysia()
|
|||||||
// Sync status
|
// Sync status
|
||||||
.get("/", async ({ sessionId }) => {
|
.get("/", async ({ sessionId }) => {
|
||||||
const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(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;
|
return latestSyncState;
|
||||||
})
|
})
|
||||||
// Run sync
|
// Run sync
|
||||||
@@ -387,10 +384,10 @@ export const app = new Elysia()
|
|||||||
)
|
)
|
||||||
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
||||||
const pProduct = await s.Commerce.Printful.Products.get(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];
|
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);
|
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
||||||
|
|
||||||
@@ -423,7 +420,7 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||||
const wOrder = await s.Commerce.Webflow.Orders.get(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}`);
|
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() }) })
|
}, { params: t.Object({ wOrderId: t.String() }) })
|
||||||
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
|
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||||
const wOrder = await s.Commerce.Webflow.Orders.get(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}`);
|
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({
|
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||||
type: "apparel_order_create",
|
type: "apparel_order_create",
|
||||||
@@ -466,14 +463,14 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const event = await s.Events.get(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) };
|
return { ...event, status: EventsService.status(event) };
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.post("/:id/retry", async ({ params: { id } }) => {
|
.post("/:id/retry", async ({ params: { id } }) => {
|
||||||
const retried = await s.Events.retry(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 })
|
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
|
// TODO: for added security, could enforce bot or admin only access
|
||||||
.get("/:id/stats", async ({ params: { id } }) => {
|
.get("/:id/stats", async ({ params: { id } }) => {
|
||||||
const stats = await s.Accounts.stats(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;
|
return stats;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: AccountIdSchema })
|
params: t.Object({ id: AccountIdSchema })
|
||||||
@@ -508,7 +505,7 @@ export const app = new Elysia()
|
|||||||
.guard({ authAdmin: true }, (app) => app
|
.guard({ authAdmin: true }, (app) => app
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const account = await s.Accounts.get(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;
|
return account;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: AccountIdSchema })
|
params: t.Object({ id: AccountIdSchema })
|
||||||
@@ -517,7 +514,7 @@ export const app = new Elysia()
|
|||||||
.group("/me", { auth: true }, (app) => app
|
.group("/me", { auth: true }, (app) => app
|
||||||
.get("/stats", async ({ accountId }) => {
|
.get("/stats", async ({ accountId }) => {
|
||||||
const stats = await s.Accounts.stats(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;
|
return stats;
|
||||||
})
|
})
|
||||||
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
|
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
|
||||||
@@ -534,7 +531,7 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
|
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
|
||||||
const deleted = await s.Assessments.delete(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 })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
@@ -553,12 +550,12 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.post("/verifications", async ({ body: { assessmentId }, accountId }) => {
|
.post("/verifications", async ({ body: { assessmentId }, accountId }) => {
|
||||||
const assessment = await s.Assessments.get(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
|
// TODO: only allow a single active non-completed verification at a time
|
||||||
|
|
||||||
const created = await s.Verifications.create(assessmentId);
|
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) };
|
return { ...created, uploadUrls: presignVerificationUploads(assessmentId) };
|
||||||
}, {
|
}, {
|
||||||
@@ -568,10 +565,10 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.post("/verifications/:id/reopen", async ({ params: { id }, accountId }) => {
|
.post("/verifications/:id/reopen", async ({ params: { id }, accountId }) => {
|
||||||
const verification = await s.Verifications.get(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);
|
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) };
|
return { ...reopened, uploadUrls: presignVerificationUploads(verification.assessment_id) };
|
||||||
}, {
|
}, {
|
||||||
@@ -579,11 +576,11 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.post("/verifications/:id/submit", async ({ params: { id }, accountId }) => {
|
.post("/verifications/:id/submit", async ({ params: { id }, accountId }) => {
|
||||||
const verification = await s.Verifications.get(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") {
|
if (verification.status === "draft") {
|
||||||
const { contents } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/`, maxKeys: 1 });
|
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);
|
const submitted = await s.Verifications.submit(id);
|
||||||
@@ -593,9 +590,9 @@ export const app = new Elysia()
|
|||||||
}
|
}
|
||||||
|
|
||||||
const current = await s.Verifications.get(id, accountId);
|
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 };
|
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 })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
@@ -615,7 +612,7 @@ export const app = new Elysia()
|
|||||||
})
|
})
|
||||||
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
||||||
const updated = await s.Assessments.update(id, player, activityPerformances);
|
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;
|
return updated;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema }),
|
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
|
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth
|
||||||
.get("/:id", async ({ params: { id } }) => {
|
.get("/:id", async ({ params: { id } }) => {
|
||||||
const verification = await s.Verifications.get(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 { contents = [] } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/` });
|
||||||
const media = contents.map(({ key, size, lastModified }) => ({
|
const media = contents.map(({ key, size, lastModified }) => ({
|
||||||
@@ -665,8 +662,8 @@ export const app = new Elysia()
|
|||||||
if (updated) return updated;
|
if (updated) return updated;
|
||||||
|
|
||||||
const verification = await s.Verifications.get(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");
|
||||||
return status(409, { error: `Cannot request action on a ${verification.status} verification` });
|
throw new ConflictError(`Cannot request action on a ${verification.status} verification`);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
@@ -679,14 +676,14 @@ export const app = new Elysia()
|
|||||||
const portalSession = auth.value && await jwt.verify(auth.value);
|
const portalSession = auth.value && await jwt.verify(auth.value);
|
||||||
const completerId = completedBy ?? (portalSession ? portalSession.accountId?.toString() : undefined);
|
const completerId = completedBy ?? (portalSession ? portalSession.accountId?.toString() : undefined);
|
||||||
const completer = completerId && await s.Accounts.get(completerId);
|
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);
|
const updated = await s.Verifications.complete(id, completer.id, activityVerifications);
|
||||||
if (updated) return updated;
|
if (updated) return updated;
|
||||||
|
|
||||||
const verification = await s.Verifications.get(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");
|
||||||
return status(409, { error: `Cannot complete a ${verification.status} verification` });
|
throw new ConflictError(`Cannot complete a ${verification.status} verification`);
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
@@ -700,7 +697,7 @@ export const app = new Elysia()
|
|||||||
.post("/webhooks/printful", async ({ body, query }) => {
|
.post("/webhooks/printful", async ({ body, query }) => {
|
||||||
// https://webflow.com/integrations/printful
|
// https://webflow.com/integrations/printful
|
||||||
if (!s.Commerce.Printful.Util.verifySecret(query.secret))
|
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;
|
const payload = body as Printful.Webhook.EventPayload;
|
||||||
|
|
||||||
@@ -723,7 +720,7 @@ export const app = new Elysia()
|
|||||||
const pProduct = payload.data.sync_product;
|
const pProduct = payload.data.sync_product;
|
||||||
const wProductId = pProduct.external_id.split("-")[0];
|
const wProductId = pProduct.external_id.split("-")[0];
|
||||||
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
|
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({
|
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||||
type: "apparel_sync_delete",
|
type: "apparel_sync_delete",
|
||||||
@@ -755,7 +752,7 @@ export const app = new Elysia()
|
|||||||
}, { query: t.Object({ secret: t.String() }) })
|
}, { query: t.Object({ secret: t.String() }) })
|
||||||
.post("/webhooks/webflow", async ({ request, body }) => {
|
.post("/webhooks/webflow", async ({ request, body }) => {
|
||||||
if (!s.Commerce.Webflow.Util.verifySecret(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;
|
const payload = body as Webflow.Webhook.EventPayload;
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ import { Value } from "@sinclair/typebox/value";
|
|||||||
|
|
||||||
export class CalculatorUnavailableError extends Error {
|
export class CalculatorUnavailableError extends Error {
|
||||||
status: number = 503
|
status: number = 503
|
||||||
|
|
||||||
|
toResponse() {
|
||||||
|
return new Response(JSON.stringify({ error: this.message }), {
|
||||||
|
status: this.status,
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CalculatorService {
|
export class CalculatorService {
|
||||||
|
|||||||
@@ -42,6 +42,36 @@ export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_
|
|||||||
export const DEFAULT_NAME = "Default";
|
export const DEFAULT_NAME = "Default";
|
||||||
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
||||||
|
|
||||||
|
export class HttpError extends Error {
|
||||||
|
constructor(public status: number, message: string) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
toResponse() {
|
||||||
|
return Response.json({ error: this.message }, { status: this.status });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BadRequestError extends HttpError {
|
||||||
|
constructor(message: string) { super(400, message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UnauthorizedError extends HttpError {
|
||||||
|
constructor(message: string) { super(401, message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ForbiddenError extends HttpError {
|
||||||
|
constructor(message: string) { super(403, message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ConflictError extends HttpError {
|
||||||
|
constructor(message: string) { super(409, message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BadGatewayError extends HttpError {
|
||||||
|
constructor(message: string) { super(502, message); }
|
||||||
|
}
|
||||||
|
|
||||||
export const BigIntIdSchema = t.String({ pattern: "^\\d+$" });
|
export const BigIntIdSchema = t.String({ pattern: "^\\d+$" });
|
||||||
export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" });
|
export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" });
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,13 @@ export class PrintfulError extends Error {
|
|||||||
public status: number = 502
|
public status: number = 502
|
||||||
) {
|
) {
|
||||||
super(message);
|
super(message);
|
||||||
this.name = "PrintfulError";
|
}
|
||||||
|
|
||||||
|
toResponse() {
|
||||||
|
return new Response(JSON.stringify({ error: this.message }), {
|
||||||
|
status: this.status,
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,13 @@ export class WebflowError extends Error {
|
|||||||
public status: number = 502
|
public status: number = 502
|
||||||
) {
|
) {
|
||||||
super(message);
|
super(message);
|
||||||
this.name = "WebflowError";
|
}
|
||||||
|
|
||||||
|
toResponse() {
|
||||||
|
return new Response(JSON.stringify({ error: this.message }), {
|
||||||
|
status: this.status,
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user