55 lines
2.3 KiB
TypeScript
55 lines
2.3 KiB
TypeScript
import { getGameDb, persist } from '@/lib/db/client';
|
|
import * as schema from '@/lib/db/schema';
|
|
import { getStateSnapshot } from '@/lib/game/state';
|
|
import { tickNow } from '@/lib/sim/engine';
|
|
|
|
// TEST-ONLY hook (v0.46.0, ISS-088) — sets the account's cash to an ABSOLUTE value so the e2e suite
|
|
// can stage exact balances (e.g. drain it below a refuel cost to test grounding, then restore it).
|
|
// Disabled unless FLIGHT_TEST_HOOKS=1 (set in docker-compose.yml for the e2e instance only); every
|
|
// other deployment 404s here. Sibling of /api/test/add-cash — same gate, same conventions; add-cash
|
|
// stays for relative grants, this one is exact.
|
|
//
|
|
// POST /api/test/set-cash
|
|
// body { amount: number } — required; a finite number in [0, ∞) (400 otherwise). Sets
|
|
// account.cash to exactly that value and returns the full state snapshot after ticking.
|
|
|
|
export async function POST(req: Request) {
|
|
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
|
|
return Response.json({ error: 'test hooks disabled' }, { status: 404 });
|
|
}
|
|
|
|
let body: unknown = {};
|
|
try {
|
|
const text = await req.text();
|
|
body = text ? JSON.parse(text) : {};
|
|
} catch {
|
|
return Response.json({ error: 'invalid JSON body' }, { status: 400 });
|
|
}
|
|
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
return Response.json({ error: 'body must be a JSON object' }, { status: 400 });
|
|
}
|
|
const input = body as Record<string, unknown>;
|
|
for (const key of Object.keys(input)) {
|
|
if (key !== 'amount') {
|
|
return Response.json({ error: `unknown field "${key}"` }, { status: 400 });
|
|
}
|
|
}
|
|
const amount = input.amount;
|
|
if (typeof amount !== 'number' || !Number.isFinite(amount) || amount < 0) {
|
|
return Response.json({ error: 'amount is required and must be a finite number >= 0' }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
const inst = await getGameDb();
|
|
await tickNow(); // clock is current before the snapshot we return (same as siblings)
|
|
const account = (await inst.db.select().from(schema.account))[0];
|
|
if (!account) throw new Error('account row missing');
|
|
await inst.db.update(schema.account).set({ cash: Math.round(amount * 100) / 100 });
|
|
await persist(inst);
|
|
return Response.json(await getStateSnapshot());
|
|
} catch (err) {
|
|
console.error('test hook failed', err);
|
|
return Response.json({ error: 'test hook failed' }, { status: 500 });
|
|
}
|
|
}
|