Files
photoreport/apps/api/test/helpers.ts
spark fcf133f94d
ci / rust (push) Successful in 7m12s
ci / typescript (push) Successful in 8m41s
Sports data: Liga, FPF and FPA squads and fixtures; player codes; events from matches
Rebuilds the old app's code-replacement system as apps/api/src/sports. The worker reads Liga Portugal
(teams, squads with numbers and headshots, fixtures), FPA (all national handball competitions) and FPF
(competitions by link, line-ups from match sheets) every 6 h. Organisations generate their code list from
it (same prefixes and templates as before, kept in a block the editor's own lines override, refreshed when
squads change), create events by picking the match, and get both squads as people (headshots as face
references with biometrics on). Face number suggestions use the event's squads.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 01:54:12 +01:00

58 lines
2.9 KiB
TypeScript

import type { FastifyInstance } from "fastify";
import { hashPassword } from "../src/auth/passwords.js";
import { buildApp } from "../src/app.js";
import { loadConfig, type Config } from "../src/config.js";
import { createDb, type Db } from "../src/db.js";
import type { Role } from "../src/generated/prisma/client.js";
import type { Broadcaster } from "../src/realtime.js";
import { assertTestDatabase } from "./guard.js";
export interface TestContext {
app: FastifyInstance;
db: Db;
config: Config;
}
export async function createTestApp(overrides: Record<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch): Promise<TestContext> {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST),
JWT_SECRET: "test-secret-test-secret-test-secret-123",
APP_PUBLIC_URL: "https://app.test.photoreport.pt",
LOGIN_RATE_LIMIT_PER_MIN: "1000",
...overrides,
});
const db = createDb(config.DATABASE_URL);
const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }) });
return { app, db, config };
}
export async function resetDb(db: Db): Promise<void> {
await db.$executeRawUnsafe(
'TRUNCATE "faces", "face_groups", "people", "delivery_items", "delivery_targets", "jersey_samples", "legacy_imports", "pending_uploads", "print_jobs", "printers", "print_stations", "print_events", "photos", "event_assignments", "events", "ftp_accounts", "code_lists", "sessions", "device_authorizations", "user_preferences", "memberships", "organizations", "users", "sports_fixtures", "sports_players", "sports_competition_teams", "sports_teams", "sports_competitions" CASCADE',
);
}
export const PASSWORD = "correct horse battery";
export async function seedUser(db: Db, email: string, opts: { org?: string; role?: Role } = {}) {
const user = await db.user.create({
data: { email, name: email.split("@")[0] ?? email, passwordHash: await hashPassword(PASSWORD), preferences: { create: {} } },
});
if (!opts.org) return { user, org: undefined };
const org =
(await db.organization.findUnique({ where: { slug: opts.org } })) ??
(await db.organization.create({ data: { slug: opts.org, name: opts.org } }));
await db.membership.create({ data: { userId: user.id, organizationId: org.id, role: opts.role ?? "PHOTOGRAPHER" } });
return { user, org };
}
export async function login(app: FastifyInstance, email: string, client: "web" | "desktop" = "web") {
const res = await app.inject({ method: "POST", url: "/v1/auth/login", payload: { email, password: PASSWORD, client } });
if (res.statusCode !== 200) throw new Error(`login failed: ${res.statusCode} ${res.body}`);
const cookie = res.cookies.find((c) => c.name === "pr_refresh");
return { body: res.json() as { accessToken: string; refreshToken?: string }, cookie: cookie?.value };
}
export const bearer = (token: string) => ({ authorization: `Bearer ${token}` });