Breakout util into seperate files

This commit is contained in:
Dominic Ferrando
2026-10-04 00:07:19 -04:00
parent 0501e63dc7
commit 0576421368
20 changed files with 78 additions and 65 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,7 +4,8 @@ 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";
+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));
+6 -2
View File
@@ -11,7 +11,11 @@ import {
Printful,
Webflow,
} from "@blade-and-brawn/commerce";
import { AccountIdSchema, BadGatewayError, BadRequestError, BigIntIdSchema, ConflictError, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, ForbiddenError, HttpError, log, UnauthorizedError } 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";
@@ -37,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();
+5 -3
View File
@@ -1,6 +1,6 @@
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";
@@ -16,11 +16,13 @@ export class CalculatorUnavailableError extends Error {
}
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([
+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,47 +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 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 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;
@@ -89,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"
},