120 lines
4.0 KiB
TypeScript
120 lines
4.0 KiB
TypeScript
import type { AddressInfo } from "node:net";
|
||
import { createApp } from "../src/app.ts";
|
||
import type { AppEnv } from "../src/config.ts";
|
||
import { type Db, migrate, openDatabase } from "../src/db/database.ts";
|
||
import { seedDemo } from "../src/seed.ts";
|
||
|
||
export const NURA_KEY = "mock-fandomat-key-nura-001";
|
||
export const ESIL_KEY = "mock-fandomat-key-esil-001";
|
||
export const COFFEE = "reward-demo-coffee";
|
||
|
||
export interface ApiResponse {
|
||
status: number;
|
||
// biome-ignore lint/suspicious/noExplicitAny: тестам удобно обращаться к полям ответа напрямую
|
||
body: any;
|
||
}
|
||
|
||
export interface TestApp {
|
||
db: Db;
|
||
baseUrl: string;
|
||
close(): Promise<void>;
|
||
request(
|
||
method: string,
|
||
path: string,
|
||
opts?: { token?: string; body?: unknown; headers?: Record<string, string> },
|
||
): Promise<ApiResponse>;
|
||
login(login: string): Promise<string>;
|
||
sendEvent(event: Record<string, unknown>, key?: string): Promise<ApiResponse>;
|
||
/** Начисляет `points` баллов жителю через событие фандомата (n × PET 500 мл). */
|
||
grantPoints(residentCode: string, points: number): Promise<void>;
|
||
balance(token: string): Promise<number>;
|
||
}
|
||
|
||
let eventSeq = 0;
|
||
|
||
export async function startTestApp(
|
||
opts: { appEnv?: AppEnv; seed?: boolean } = {},
|
||
): Promise<TestApp> {
|
||
const db = openDatabase(":memory:");
|
||
migrate(db);
|
||
if (opts.seed ?? true) seedDemo(db);
|
||
const server = createApp({ db, appEnv: opts.appEnv ?? "test" });
|
||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||
const { port } = server.address() as AddressInfo;
|
||
const baseUrl = `http://127.0.0.1:${port}`;
|
||
|
||
const request: TestApp["request"] = async (method, path, o = {}) => {
|
||
const headers: Record<string, string> = { ...o.headers };
|
||
if (o.token) headers.authorization = `Bearer ${o.token}`;
|
||
if (o.body !== undefined) headers["content-type"] = "application/json";
|
||
const res = await fetch(baseUrl + path, {
|
||
method,
|
||
headers,
|
||
body: o.body === undefined ? undefined : JSON.stringify(o.body),
|
||
});
|
||
const text = await res.text();
|
||
return { status: res.status, body: text ? JSON.parse(text) : undefined };
|
||
};
|
||
|
||
const app: TestApp = {
|
||
db,
|
||
baseUrl,
|
||
request,
|
||
async close() {
|
||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||
db.close();
|
||
},
|
||
async login(login) {
|
||
const res = await request("POST", "/api/auth/dev-login", { body: { login } });
|
||
if (res.status !== 200) throw new Error(`login ${login} failed: ${JSON.stringify(res.body)}`);
|
||
return res.body.token as string;
|
||
},
|
||
sendEvent(event, key = NURA_KEY) {
|
||
return request("POST", "/api/fandomats/events", {
|
||
body: event,
|
||
headers: { "x-fandomat-key": key },
|
||
});
|
||
},
|
||
async grantPoints(residentCode, points) {
|
||
const res = await app.sendEvent(
|
||
petEvent(`grant-${++eventSeq}`, residentCode, [
|
||
{ type: "pet", volumeMl: 500, count: points },
|
||
]),
|
||
);
|
||
if (res.body?.outcome !== "credited")
|
||
throw new Error(`grant failed: ${JSON.stringify(res.body)}`);
|
||
},
|
||
async balance(token) {
|
||
return (await request("GET", "/api/me/points", { token })).body.balance as number;
|
||
},
|
||
};
|
||
return app;
|
||
}
|
||
|
||
export function petEvent(
|
||
eventId: string,
|
||
residentCode: string | null,
|
||
items: unknown[] = [
|
||
{ type: "pet", volumeMl: 500, count: 3 },
|
||
{ type: "aluminum", volumeMl: 330, count: 2 },
|
||
],
|
||
extra: Record<string, unknown> = {},
|
||
): Record<string, unknown> {
|
||
return {
|
||
eventId,
|
||
fandomatId: "FM-NURA-001",
|
||
status: "confirmed",
|
||
...(residentCode === null ? {} : { residentCode }),
|
||
items,
|
||
...extra,
|
||
};
|
||
}
|
||
|
||
/** Сумма записей истории — должна совпадать с балансом. */
|
||
export function ledgerSum(db: Db, userId: string): number {
|
||
const row = db
|
||
.prepare("SELECT COALESCE(SUM(delta), 0) AS s FROM point_ledger WHERE user_id = ?")
|
||
.get(userId);
|
||
return Number(row?.s ?? 0);
|
||
}
|