Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x | // Admin cost-calculator config endpoints.
//
// GET /calculator-config — current config (falls back to the bundled default
// when nothing has been saved yet).
// PUT /calculator-config — validate + persist a new config, bump version, and
// invalidate the marketplace KV cache so edits land
// immediately. Body is the full CalculatorConfig.
import { type Context, Hono } from "hono";
import { ZodError } from "zod";
import type { Dal } from "../../dal";
import { CACHE_KEYS, createDualCache } from "../../lib/cache";
import { purgeEdgeCache } from "../../lib/edge-cache";
import { logger } from "../../lib/logger";
import { handleError, success } from "../../lib/response";
import { requireUser } from "../../lib/utils";
import type { Services } from "../../services";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const calculatorConfig = new Hono<Env>();
function invalidateConfigCache(c: Context<Env>) {
try {
const cache = createDualCache(c.env.KV_CACHE);
// Edge (Cloudflare Cache API) forces a 30-min TTL on marketplace GETs, so
// a KV delete alone isn't enough — purge the edge entry too so admin edits
// land immediately rather than after the edge TTL expires.
const edgeUrl = new URL(
"/api/marketplace/calculator-config",
c.req.url,
).toString();
c.executionCtx.waitUntil(
Promise.all([
cache.delete(CACHE_KEYS.CALCULATOR_CONFIG),
purgeEdgeCache(edgeUrl),
]).catch((err) => {
logger.error(
"[admin/calculator-config] cache invalidation failed",
err,
);
}),
);
} catch {
/* executionCtx unavailable in tests */
}
}
calculatorConfig.get("/", async (c) => {
try {
requireUser(c.get("user"));
const config = await c.get("services").calculatorConfig.getConfig();
return success(c, config);
} catch (err) {
return handleError(c, err);
}
});
calculatorConfig.put("/", async (c) => {
try {
requireUser(c.get("user"));
const body = await c.req.json();
const config = await c.get("services").calculatorConfig.updateConfig(body);
invalidateConfigCache(c);
return success(c, config);
} catch (err) {
Eif (err instanceof ZodError) {
return c.json(
{
success: false,
error: { message: "Invalid calculator config", issues: err.issues },
},
400,
);
}
return handleError(c, err);
}
});
export default calculatorConfig;
|