3 Commits
Author SHA1 Message Date
Dominic Ferrando 0576421368 Breakout util into seperate files 2026-10-04 00:07:19 -04:00
Dominic Ferrando 0501e63dc7 More cleanup 2026-10-03 23:56:55 -04:00
Dominic Ferrando 9bf60b7c8b Code cleanup 2026-10-03 23:49:16 -04:00
25 changed files with 183 additions and 118 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import { CreateTableBuilder, Kysely, PostgresDialect, sql } from 'kysely';
import { type DB } from "./out/db";
import { Pool } from "pg";
import { env, WORKER_COUNT } from '../util';
import { env, WORKER_COUNT } from '../util/env';
export const db = new Kysely<DB>({
dialect: new PostgresDialect({
+2 -1
View File
@@ -3,7 +3,8 @@ import { promises as fs } from 'fs'
import { FileMigrationProvider, Migrator, type MigrationResultSet } from 'kysely/migration'
import { db } from './db'
import { argv } from 'bun'
import { env, log } from '../util'
import { env } from '../util/env';
import { log } from '../util/log';
type HandlerResult = {
message: string;
+4 -1
View File
@@ -3,10 +3,13 @@ import {
} from "@blade-and-brawn/calculator";
import { Value } from "@sinclair/typebox/value";
import { db } from "./db";
import { DEFAULT_NAME, env, log } from "../util";
import { env } from "../util/env";
import { log } from "../util/log";
import standardsConfig from "./seed-data/standards-config.json" with {type: "json"};
import type { AccountRole } from "../services/accounts";
export const DEFAULT_NAME = "Default";
Value.Assert(StandardsConfigSchema, standardsConfig);
async function seedStandardsDataset(): Promise<string> {
+2 -1
View File
@@ -1,5 +1,6 @@
import cluster from 'node:cluster'
import { log, WORKER_COUNT } from "./util";
import { log } from "./util/log";
import { WORKER_COUNT } from "./util/env";
if (cluster.isPrimary) {
log.info(`Starting ${WORKER_COUNT} worker processes`)
+1 -1
View File
@@ -1,5 +1,5 @@
import { WebflowClient } from "@blade-and-brawn/commerce";
import { env } from "../util";
import { env } from "../util/env";
const webflow = new WebflowClient({
siteId: env.WEBFLOW_SITE_ID,
+1 -1
View File
@@ -1,5 +1,5 @@
import { Printful, PrintfulClient, PrintfulError, Webflow, WebflowClient, WebflowError } from "@blade-and-brawn/commerce";
import { env } from "../util";
import { env } from "../util/env";
const DOMAIN = env.NODE_ENV === "development" ?
"dev-api.bladeandbrawn.com" :
@@ -4,12 +4,13 @@ import { readdir } from "node:fs/promises";
import path from "node:path";
import { parseArgs } from "node:util";
import { db } from "../database/db";
import { env, log } from "../util";
import { env } from "../util/env";
import { log } from "../util/log";
import type { AccountRole } from "../services/accounts";
import { VerificationsService } from "../services/verifications";
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 { values: args } = parseArgs({
@@ -68,12 +69,12 @@ async function seedTestAssessment(accountId: string): Promise<string> {
return result.id;
}
async function uploadFixtures(assessmentId: string) {
const names = await readdir(FIXTURES_DIR).catch(() => []);
if (names.length === 0) log.warn({ dir: FIXTURES_DIR }, "no fixture media found, verification will have no media");
async function uploadMedia(assessmentId: string) {
const names = await readdir(MEDIA_DIR).catch(() => []);
if (names.length === 0) log.warn({ dir: MEDIA_DIR }, "no fixture media found, verification will have no media");
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()}`;
await r2.write(key, file, { type: file.type });
log.info({ key, name, size: file.size }, "uploaded fixture media");
@@ -96,7 +97,7 @@ async function uploadFixtures(assessmentId: string) {
const verification = await verifications.create(assessmentId);
if (!verification) throw new Error("Failed to create test verification");
await uploadFixtures(assessmentId);
await uploadMedia(assessmentId);
const submitted = await verifications.submit(verification.id);
if (!submitted) throw new Error("Failed to submit test verification");
+1 -1
View File
@@ -3,7 +3,7 @@ import {
ProductSyncer,
WebflowClient,
} from "@blade-and-brawn/commerce";
import { env } from "../util";
import { env } from "../util/env";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+66 -67
View File
@@ -2,17 +2,20 @@ import {
ActivityPerformanceSchema,
ActivityVerificationsSchema,
PlayerSchema,
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, BigIntIdSchema } from "./util/models";
import { BadGatewayError, BadRequestError, ConflictError, ForbiddenError, HttpError, UnauthorizedError } from "./util/error";
import { DUMMY_PASSWORD_HASH } from "./util/crypto";
import { env } from "./util/env";
import { log } from "./util/log";
import serverTiming from "@elysia/server-timing";
import jwt from "@elysia/jwt";
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
@@ -38,7 +41,7 @@ const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for coo
// -----------------------
const s = (() => {
const Standards = new StandardsService();
const Calculator = new CalculatorService(DEFAULT_NAME);
const Calculator = new CalculatorService();
const Commerce = new CommerceService();
const Accounts = new AccountsService(Calculator);
const Events = new EventsService();
@@ -58,12 +61,6 @@ const r2 = {
})
};
const presignVerificationUploads = (assessmentId: string) =>
Object.values(Activity).map(() => r2.verificationMedia.presign(`${assessmentId}/${crypto.randomUUID()}`, {
method: "PUT",
expiresIn: 30 * 60,
}));
// QUEUES
// -----------------------
const queues = [
@@ -117,35 +114,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")
// Database errors
if (error instanceof DatabaseError) {
if (error.code === "23505")
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 +164,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 +202,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 +222,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 +233,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 +361,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 +380,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 +416,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 +424,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 +459,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 +478,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 +501,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 +510,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 +527,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,14 +546,17 @@ 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) };
return {
...created,
uploadUrls: VerificationsService.presignMediaUploads(r2.verificationMedia, assessmentId)
};
}, {
body: t.Object({
assessmentId: BigIntIdSchema
@@ -568,22 +564,25 @@ 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) };
return {
...reopened,
uploadUrls: VerificationsService.presignMediaUploads(r2.verificationMedia, verification.assessment_id)
};
}, {
params: t.Object({ id: BigIntIdSchema })
})
.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 +592,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 +614,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 +644,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 +664,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 +678,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 +699,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 +722,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 +754,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;
+12 -3
View File
@@ -1,19 +1,28 @@
import { LevelCalculator, Standards, StandardsParamsSchema, StandardsDataSchema, type StandardsConfig, type LevelCalculatorOutput } from "@blade-and-brawn/calculator";
import type { ActivityPerformance, Player } from "@blade-and-brawn/domain";
import { log } from "../util";
import { log } from "../util/log";
import { db } from "../database/db";
import { Value } from "@sinclair/typebox/value";
export class CalculatorUnavailableError extends Error {
status: number = 503
toResponse() {
return new Response(JSON.stringify({ error: this.message }), {
status: this.status,
headers: { 'content-type': 'application/json' }
})
}
}
export class CalculatorService {
private static readonly DEFAULT_NAME = "Default";
private calculator: LevelCalculator | null = null;
Standards: CalculatorStandardsService;
constructor(private name: string) {
this.Standards = new CalculatorStandardsService(this.name);
constructor() {
this.Standards = new CalculatorStandardsService(CalculatorService.DEFAULT_NAME);
// eagerly load
this.refresh().catch((err) => log.error({ err }, "failed to load initial standards config"));
}
+2 -1
View File
@@ -1,5 +1,6 @@
import { PrintfulClient, ProductSyncer, WebflowClient } from "@blade-and-brawn/commerce";
import { env, log } from "../util";
import { env } from "../util/env";
import { log } from "../util/log";
import { db } from "../database/db";
import { defineEventType, EventQueue } from "./event-queue";
import { Type as t } from "@sinclair/typebox";
+1 -1
View File
@@ -1,6 +1,6 @@
import { type Selectable, type Transaction } from "kysely";
import type { DB } from "../database/out/db";
import { log } from "../util";
import { log } from "../util/log";
import { sleep } from "bun";
import { db } from "../database/db";
import { AssertError, Value } from "@sinclair/typebox/value";
+1 -1
View File
@@ -3,7 +3,7 @@ import { t } from "elysia";
import { sql, type Selectable, type Transaction } from "kysely";
import type { DB, JsonValue } from "../database/out/db";
import { db } from "../database/db";
import { log } from "../util";
import { log } from "../util/log";
import { minToMs } from "@blade-and-brawn/domain";
export const EventStatusSchema = t.Union([
+17 -9
View File
@@ -3,6 +3,7 @@ import type { Static } from "@sinclair/typebox";
import { t } from "elysia";
import { db } from "../database/db";
import { AccountsService } from "./accounts";
import { S3Client } from "bun";
export const VerificationStatusSchema = t.Union([
t.Literal("draft"),
@@ -21,6 +22,13 @@ const ALLOWED_FROM = {
} satisfies Record<string, VerificationStatus[]>;
export class VerificationsService {
public static presignMediaUploads(s3Client: S3Client, assessmentId: string) {
return Object.values(Activity).map(() => s3Client.presign(`${assessmentId}/${crypto.randomUUID()}`, {
method: "PUT",
expiresIn: 30 * 60,
}))
}
async create(assessmentId: string) {
return await db.insertInto("verifications")
.values({ assessment_id: assessmentId, status: "draft" satisfies VerificationStatus })
@@ -29,15 +37,6 @@ export class VerificationsService {
.executeTakeFirst();
}
async reopen(id: string) {
return await db.updateTable("verifications")
.where("id", "=", id)
.where("status", "in", ALLOWED_FROM.reopen)
.set({ status: "draft" satisfies VerificationStatus, submitted_at: null })
.returning(["id", "status"])
.executeTakeFirst();
}
async get(id: string, accountId?: string) {
return await VerificationsService.baseQuery()
.where("verifications.id", "=", id)
@@ -110,6 +109,15 @@ export class VerificationsService {
.executeTakeFirst();
}
async reopen(id: string) {
return await db.updateTable("verifications")
.where("id", "=", id)
.where("status", "in", ALLOWED_FROM.reopen)
.set({ status: "draft" satisfies VerificationStatus, submitted_at: null })
.returning(["id", "status"])
.executeTakeFirst();
}
private static accountIdQuery(accountId: string) {
return db.selectFrom("accounts")
.select("id")
+4
View File
@@ -0,0 +1,4 @@
import { createHash } from "node:crypto";
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
export const sha256Sum = (s: string) => createHash("sha256").update(s).digest();
@@ -1,15 +1,5 @@
import cluster from 'node:cluster';
import { createHash } from 'node:crypto';
import { pino } from 'pino';
import os from 'node:os'
import { t } from 'elysia';
export const log = pino({
level: Bun.env.LOG_LEVEL ?? "info",
transport: Bun.env.NODE_ENV != "production"
? { target: "pino-pretty" }
: undefined,
});
export const env = {
PRINTFUL_AUTH: requireEnv("PRINTFUL_AUTH"),
@@ -39,17 +29,12 @@ export const env = {
};
export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_COUNT);
export const DEFAULT_NAME = "Default";
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
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})$" });
function requireEnv(key: string): string {
const val = Bun.env[key];
if (!val) {
if (cluster.worker?.id === 1)
log.error({ name: key }, "Missing required environment variable");
console.error({ name: key }, "Missing required environment variable");
throw new Error(`Missing required environment variable: ${key}`)
};
return val;
@@ -59,10 +44,8 @@ function optionEnv(key: string, fallback: string = ""): string {
const val = Bun.env[key];
if (!val) {
if (cluster.worker?.id === 1)
log.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`)
console.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`)
return fallback
};
return val;
}
export const sha256Sum = (s: string) => createHash("sha256").update(s).digest();
+29
View File
@@ -0,0 +1,29 @@
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); }
}
+8
View File
@@ -0,0 +1,8 @@
import { pino } from 'pino';
export const log = pino({
level: Bun.env.LOG_LEVEL ?? "info",
transport: Bun.env.NODE_ENV != "production"
? { target: "pino-pretty" }
: undefined,
});
+4
View File
@@ -0,0 +1,4 @@
import { t } from 'elysia';
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})$" });
+1
View File
@@ -11,6 +11,7 @@
},
"devDependencies": {
"@types/bun": "^1.4.2",
"@types/node": "^26.6.4",
"@typescript/native": "npm:typescript@7",
"typescript": "~6",
},
+1
View File
@@ -14,6 +14,7 @@
},
"devDependencies": {
"@types/bun": "^1.4.2",
"@types/node": "^26.6.4",
"@typescript/native": "npm:typescript@7",
"typescript": "~6"
},
+7 -1
View File
@@ -25,7 +25,13 @@ export class PrintfulError extends Error {
public status: number = 502
) {
super(message);
this.name = "PrintfulError";
}
toResponse() {
return new Response(JSON.stringify({ error: this.message }), {
status: this.status,
headers: { 'content-type': 'application/json' }
})
}
}
+7 -1
View File
@@ -32,7 +32,13 @@ export class WebflowError extends Error {
public status: number = 502
) {
super(message);
this.name = "WebflowError";
}
toResponse() {
return new Response(JSON.stringify({ error: this.message }), {
status: this.status,
headers: { 'content-type': 'application/json' }
})
}
}