feat: scaffold frontend app structure

This commit is contained in:
Anton
2026-04-06 15:15:53 +03:00
parent 698ae37553
commit d7fb5b71ef
29 changed files with 2753 additions and 56 deletions

View File

@@ -11,14 +11,27 @@ function requireEnv(name: string): string {
return value;
}
const useMockDb =
process.env.CALENDAR_RUN_MOCK_DB === "1" ||
process.env.CALENDAR_RUN_MOCK_DB?.toLowerCase() === "true";
export const config = {
db: {
host: requireEnv("DB_HOST"),
port: parseInt(requireEnv("DB_PORT"), 10),
database: requireEnv("DB_NAME"),
user: requireEnv("DB_USER"),
password: requireEnv("DB_PASSWORD"),
},
apiPort: parseInt(process.env.API_PORT || "3001", 10),
useMockDb,
db: useMockDb
? {
host: "mock",
port: 5432,
database: "mock",
user: "mock",
password: "mock",
}
: {
host: requireEnv("DB_HOST"),
port: parseInt(requireEnv("DB_PORT"), 10),
database: requireEnv("DB_NAME"),
user: requireEnv("DB_USER"),
password: requireEnv("DB_PASSWORD"),
},
apiPort: parseInt(process.env.PORT || process.env.API_PORT || "3001", 10),
corsOrigin: process.env.CORS_ORIGIN || "http://localhost:5173",
};

View File

@@ -1,5 +1,6 @@
import { Pool, PoolConfig } from "pg";
import { Pool, PoolConfig, QueryResult, QueryResultRow } from "pg";
import { config } from "./config";
import type { RaceRow } from "./mappers/race";
const poolConfig: PoolConfig = {
host: config.db.host,
@@ -12,13 +13,119 @@ const poolConfig: PoolConfig = {
connectionTimeoutMillis: 5_000,
};
export const pool = new Pool(poolConfig);
function mockRowFromInsert(sql: string, params: unknown[]): RaceRow {
const match = sql.match(/INSERT INTO races\s*\(([^)]+)\)\s*VALUES/i);
const now = new Date().toISOString();
if (!match) {
return {
id: String(params[0] ?? ""),
race_date: "",
title: "",
distance_km: "0",
status: null,
official_url: null,
start_time: null,
cluster_schedule: null,
bib_pickup: null,
bib_number: null,
finish_time: null,
notes: null,
created_at: now,
updated_at: null,
};
}
const cols = match[1].split(",").map((c) => c.trim());
const row: Record<string, unknown> = {};
cols.forEach((col, i) => {
row[col] = params[i];
});
return {
id: String(row.id ?? ""),
race_date: String(row.race_date ?? ""),
title: String(row.title ?? ""),
distance_km: String(row.distance_km ?? "0"),
status: row.status != null ? String(row.status) : null,
official_url: row.official_url != null ? String(row.official_url) : null,
start_time: row.start_time != null ? String(row.start_time) : null,
cluster_schedule: row.cluster_schedule != null ? String(row.cluster_schedule) : null,
bib_pickup: row.bib_pickup != null ? String(row.bib_pickup) : null,
bib_number: row.bib_number != null ? String(row.bib_number) : null,
finish_time: row.finish_time != null ? String(row.finish_time) : null,
notes: row.notes != null ? String(row.notes) : null,
created_at: now,
updated_at: null,
};
}
pool.on("error", (err) => {
console.error("[db] Unexpected pool error:", err.message);
});
function createMockPool(): Pool {
const emptyResult = <T extends QueryResultRow>(): QueryResult<T> =>
({
rows: [],
rowCount: 0,
command: "",
oid: 0,
fields: [],
}) as QueryResult<T>;
const mockQuery = async <T extends QueryResultRow>(
text: string,
params?: unknown[],
): Promise<QueryResult<T>> => {
const sql = text.replace(/\s+/g, " ").trim();
const p = params ?? [];
if (sql.includes("DELETE FROM races")) {
return emptyResult();
}
if (sql.includes("INSERT INTO races") && sql.includes("RETURNING")) {
const row = mockRowFromInsert(text, p);
return {
rows: [row as unknown as T],
rowCount: 1,
command: "INSERT",
oid: 0,
fields: [],
} as QueryResult<T>;
}
if (sql.includes("UPDATE races") && sql.includes("RETURNING")) {
return emptyResult();
}
if (sql.includes("SELECT * FROM races")) {
return emptyResult();
}
return emptyResult();
};
const mockPool = {
query: mockQuery,
connect: async () => {
throw new Error(
"CALENDAR_RUN_MOCK_DB is enabled: migrate/seed require a real database; unset CALENDAR_RUN_MOCK_DB and configure DB_*.",
);
},
end: async () => {},
on() {
return mockPool;
},
};
return mockPool as unknown as Pool;
}
export const pool = config.useMockDb ? createMockPool() : new Pool(poolConfig);
if (!config.useMockDb) {
pool.on("error", (err) => {
console.error("[db] Unexpected pool error:", err.message);
});
} else {
console.warn("[db] Mock database enabled (CALENDAR_RUN_MOCK_DB); no PostgreSQL connection is used.");
}
export async function checkDbConnection(): Promise<boolean> {
if (config.useMockDb) {
return true;
}
try {
const client = await pool.connect();
client.release();

View File

@@ -4,26 +4,77 @@ import { rowToDto, bodyToColumns, RaceRow } from "../mappers/race";
const router = Router();
type ValidationErrorBody = {
error: "validation_error";
details: string[];
};
function dbError(res: Response) {
res.status(503).json({ error: "database_unavailable" });
}
function validationError(res: Response, details: string[]) {
const body: ValidationErrorBody = { error: "validation_error", details };
res.status(400).json(body);
}
function parseOptionalIntegerQuery(
value: unknown,
fieldName: string,
min?: number,
max?: number,
): { value?: number; error?: string } {
if (value == null) {
return {};
}
if (typeof value !== "string" || value.trim() === "") {
return { error: `${fieldName} must be an integer` };
}
const normalized = value.trim();
if (!/^-?\d+$/.test(normalized)) {
return { error: `${fieldName} must be an integer` };
}
const parsed = Number(normalized);
if (!Number.isInteger(parsed)) {
return { error: `${fieldName} must be an integer` };
}
if (min != null && parsed < min) {
return { error: `${fieldName} must be between ${min} and ${max}` };
}
if (max != null && parsed > max) {
return { error: `${fieldName} must be between ${min} and ${max}` };
}
return { value: parsed };
}
/* ─── GET /races ──────────────────────────────────────────── */
router.get("/races", async (req: Request, res: Response) => {
const yearResult = parseOptionalIntegerQuery(req.query.year, "year");
const monthResult = parseOptionalIntegerQuery(req.query.month, "month", 1, 12);
const details = [yearResult.error, monthResult.error].filter(Boolean) as string[];
if (details.length > 0) {
validationError(res, details);
return;
}
try {
const { year, month } = req.query;
const conditions: string[] = [];
const params: unknown[] = [];
let idx = 1;
if (year) {
if (yearResult.value != null) {
conditions.push(`EXTRACT(YEAR FROM race_date) = $${idx++}`);
params.push(Number(year));
params.push(yearResult.value);
}
if (month) {
if (monthResult.value != null) {
conditions.push(`EXTRACT(MONTH FROM race_date) = $${idx++}`);
params.push(Number(month));
params.push(monthResult.value);
}
const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
@@ -46,7 +97,7 @@ router.get("/races/:id", async (req: Request, res: Response) => {
[req.params.id],
);
if (rows.length === 0) {
res.status(404).json({ error: "not_found" });
res.status(404).json({ error: "not_found", details: ["Race not found"] });
return;
}
res.json(rowToDto(rows[0]));
@@ -62,10 +113,7 @@ router.post("/races", async (req: Request, res: Response) => {
const body = req.body;
if (!body.id || !body.date || !body.title || body.distanceKm == null) {
res.status(400).json({
error: "validation_error",
details: ["Fields id, date, title, distanceKm are required"],
});
validationError(res, ["Fields id, date, title, distanceKm are required"]);
return;
}
@@ -81,7 +129,10 @@ router.post("/races", async (req: Request, res: Response) => {
res.status(201).json(rowToDto(rows[0]));
} catch (err: any) {
if (err.code === "23505") {
res.status(409).json({ error: "conflict", details: ["Race with this id already exists"] });
res.status(409).json({
error: "conflict",
details: ["Race with this id already exists"],
});
return;
}
console.error("[POST /races]", err);
@@ -95,10 +146,7 @@ router.patch("/races/:id", async (req: Request, res: Response) => {
const { columns, values } = bodyToColumns(req.body);
if (columns.length === 0) {
res.status(400).json({
error: "validation_error",
details: ["No updatable fields provided"],
});
validationError(res, ["No updatable fields provided"]);
return;
}
@@ -110,7 +158,7 @@ router.patch("/races/:id", async (req: Request, res: Response) => {
try {
const { rows } = await pool.query<RaceRow>(sql, values);
if (rows.length === 0) {
res.status(404).json({ error: "not_found" });
res.status(404).json({ error: "not_found", details: ["Race not found"] });
return;
}
res.json(rowToDto(rows[0]));
@@ -129,7 +177,7 @@ router.delete("/races/:id", async (req: Request, res: Response) => {
[req.params.id],
);
if (rowCount === 0) {
res.status(404).json({ error: "not_found" });
res.status(404).json({ error: "not_found", details: ["Race not found"] });
return;
}
res.status(204).end();