All files / middleware context.middleware.ts

100% Statements 10/10
100% Branches 0/0
100% Functions 1/1
100% Lines 10/10

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                                          4x 16x       16x 16x 16x   16x 16x 16x 16x   16x    
// Context Middleware - Attach DAL, Services, and Cache to request context
import type { MiddlewareHandler } from "hono";
import { createDal, type Dal } from "../dal";
import { getDb } from "../db";
import { createDualCache, type DualCache } from "../lib/cache";
import { createServices, type Services } from "../services";
 
export type ContextVariables = {
	dal: Dal;
	services: Services;
	db: ReturnType<typeof getDb>;
	cache: DualCache;
};
 
/**
 * Attach DAL, Services, DB, and Cache to request context
 * Use c.get("dal"), c.get("services"), c.get("db"), or c.get("cache") in route handlers
 */
export const contextMiddleware: MiddlewareHandler<{
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
}> = async (c, next) => {
	const db = getDb(c.env.DB);
	// Cache is constructed first and wired into the DAL so that DALs which
	// participate in cache invalidation (e.g. ConsentAttestationsDal) can
	// proactively evict stale keys on writes. See B5.a hook.
	const dualCache = createDualCache(c.env.KV_CACHE);
	const dal = createDal(db, dualCache, c.env);
	const services = createServices(dal, c.env);
 
	c.set("dal", dal);
	c.set("services", services);
	c.set("db", db);
	c.set("cache", dualCache);
 
	await next();
};