HTTP & Action Controllers

Katal implements the Action-Domain-Responder (ADR) architectural pattern via single-action controllers extending Controller.


1. Defining Action Controllers

Every controller is dedicated to a single action, providing maximum modularity, clean constructor dependency injection, and fine-grained testability:

import { Controller } from "katal";
import type { RequestContext } from "katal";
import { z } from "zod";

export class CreateUserController extends Controller {
    // 1. Static Schema Declaration: Introspected without controller instantiation
    static schema = {
        body: z.object({
            name: z.string().min(2),
            email: z.string().email(),
        }),
    };

    // 2. Constructor Dependency Injection via IoC Container
    constructor(private readonly users: UserService) {
        super();
    }

    // 3. Execution Handler
    async handle(ctx: RequestContext) {
        // Read validated and type-safe body
        const body = ctx.valid<{ name: string; email: string }>("body");

        const user = await this.users.create(body);
        return this.created(user);
    }
}

2. Static Schema Declarations (static schema)

In Katal, validation schemas on controllers are declared as static schema = ....

Key Benefits:

  • Zero Instantiation at Route Registration: The Router and OpenAPI 3.1 generator introspect validation schemas at application boot without invoking the controller's constructor. Controllers requiring database connections, repositories, or services can be registered safely without mock dependencies.
  • Route-Level Overrides: If a route passes an inline schema, it automatically takes precedence over the controller's static schema: typescript app.post("/users", CreateUserController, { schema: CustomOverrideSchema });

3. Monomorphic RequestContext Class

In Katal, the incoming request context is a pre-allocated, monomorphic class designed for V8 engine optimization:

  • Hidden-Class Stability: All properties (request, id, params, query, body, user, container) are initialized in a fixed order in the constructor. This keeps property lookups in fast monomorphic inline caches (IC) under $>50,000$ req/s.
  • Zero Per-Request Closures: Helper methods like valid(), json(), text(), and formData() live on RequestContext.prototype, eliminating closure memory churn per request.

Available Context Helpers

// Read validated data targets (body, query, params, headers)
const body = ctx.valid<CreateUserDTO>("body");
const query = ctx.valid<PaginationQuery>("query");
const params = ctx.valid<{ id: string }>("params");

// Standard body parsers
const json = await ctx.json();
const text = await ctx.text();
const form = await ctx.formData();
const rawStream = ctx.rawBody();

4. Isolated Unit Testing

Because RequestContext is a standalone class and controllers do not require server boot, you can test action controllers in pure isolation with sub-millisecond execution:

import { test, expect } from "bun:test";
import { RequestContext } from "katal";
import { CreateUserController } from "./CreateUserController";

test("CreateUserController creates new user successfully", async () => {
    const mockUserService = {
        create: async (data) => ({ id: "usr_1", ...data }),
    };

    const controller = new CreateUserController(mockUserService as any);

    const req = new Request("http://localhost/users", { method: "POST" });
    const ctx = new RequestContext(req, {
        body: { name: "Alice", email: "alice@example.com" },
    });
    ctx.setValidated("body", { name: "Alice", email: "alice@example.com" });

    const response = await controller.handle(ctx);

    expect(response.status).toBe(201);
    const data = await response.json();
    expect(data.id).toBe("usr_1");
});

5. Built-in Response Helpers

Controllers provide RFC-compliant response helpers:

// 200 OK
return this.success({ user });

// 201 Created
return this.created({ id: "usr_1" });

// 204 No Content
return this.noContent();

// 400 Bad Request (RFC 7807 Problem Details)
return this.badRequest("Invalid input parameters");

// 401 Unauthorized
return this.unauthorized("Authentication required");

// 403 Forbidden
return this.forbidden("Insufficient permissions");

// 404 Not Found
return this.notFound("User not found");

See Also