Custom Base Controllers & Lifecycle Hooks¶
In Katal, the Controller class provides optional lifecycle hooks: beforeHandle() and afterHandle(). By creating custom abstract base controllers, you can encapsulate cross-cutting concerns (multi-tenancy, custom response formatting, audit stamping, role enforcement) cleanly across groups of controllers.
1. Lifecycle Hook Contracts¶
| Hook | Invocation Time | Return Value | Effect |
|---|---|---|---|
beforeHandle() |
Immediately before handle() |
Promise<Response \| null> \| Response \| null |
Return null to continue to handle(). Return a Response to short-circuit the request early. |
afterHandle(response) |
Immediately after handle() |
Promise<Response> \| Response |
Transform, wrap, or inject headers into the outgoing response. |
2. Pattern 1: Standard API Response Envelope (ApiController)¶
Enforce consistent JSON envelopes across your entire platform ({ success: true, timestamp: "...", data: ... }):
import { Controller } from "katal";
export abstract class ApiController extends Controller {
/**
* Intercept outgoing responses and wrap payloads in standard envelope
*/
protected override async afterHandle(response: Response): Promise<Response> {
// Do not wrap non-JSON or error problem details
const contentType = response.headers.get("Content-Type") ?? "";
if (!contentType.includes("application/json")) {
return response;
}
const rawJson = await response.json();
const wrapped = {
success: response.status >= 200 && response.status < 300,
timestamp: new Date().toISOString(),
data: rawJson.data ?? rawJson,
};
const headers = new Headers(response.headers);
headers.set("X-Framework", "Katal v3");
return new Response(JSON.stringify(wrapped), {
status: response.status,
statusText: response.statusText,
headers,
});
}
}
// Concrete Controller inheriting envelope formatting
export class GetStatsController extends ApiController {
async handle() {
return this.success({ activeUsers: 1420, dailyRevenue: 8500 });
}
}
// Outputs:
// {
// "success": true,
// "timestamp": "2026-10-14T23:55:00.000Z",
// "data": { "activeUsers": 1420, "dailyRevenue": 8500 }
// }
3. Pattern 2: Multi-Tenant Header Extraction (TenantController)¶
Automatically parse tenant context and verify organization membership before reaching business logic:
import { Controller } from "katal";
export abstract class TenantController extends Controller {
protected tenantId!: string;
protected override async beforeHandle(): Promise<Response | null> {
const tenantHeader = this.context.request.headers.get("x-tenant-id");
if (!tenantHeader) {
return this.error("Missing mandatory X-Tenant-ID header.", 400);
}
// Verify user belongs to tenant organization
if (this.context.user && this.context.user.organizationId !== tenantHeader) {
return this.error("Access to tenant organization forbidden.", 403);
}
this.tenantId = tenantHeader;
return null; // Proceed to handle()
}
}
// Concrete Controller
export class ListInvoicesController extends TenantController {
constructor(private readonly invoiceRepo: InvoiceRepository) {
super();
}
async handle() {
// this.tenantId is guaranteed to exist and be validated!
const invoices = await this.invoiceRepo.findAllForTenant(this.tenantId);
return this.success(invoices);
}
}
4. Pattern 3: Strict Role Guard Base Controller (AdminController)¶
import { Controller } from "katal";
export abstract class AdminController extends Controller {
protected override async beforeHandle(): Promise<Response | null> {
if (!this.context.user || this.context.user.role !== "admin") {
return this.error("Administrator privileges required.", 403);
}
return null;
}
}
export class PurgeCacheController extends AdminController {
async handle() {
// Guaranteed that only admins reach this method
return this.success({ message: "Cache purged successfully" });
}
}