Complete Simple Application Example¶
A complete, production-ready REST API built with Katal demonstrating foundational patterns: JWT authentication, CORS, rate limiting, static schema validation, dependency injection, and route groups.
1. Project Layout¶
my-api/
├── src/
│ ├── services/
│ │ └── UserService.ts
│ ├── controllers/
│ │ ├── AuthController.ts
│ │ └── UserController.ts
│ └── app.ts
├── package.json
└── tsconfig.json
2. Complete Application Code (src/app.ts)¶
import {
Application,
Controller,
Auth,
createAuthMiddleware,
CorsMiddleware,
createRateLimitMiddleware,
} from "katal";
import type { RequestContext } from "katal";
import { z } from "zod";
// --- 1. Domain Service ---
export class UserService {
private users = new Map<string, { id: string; name: string; email: string }>([
["1", { id: "1", name: "Alice", email: "alice@example.com" }],
["2", { id: "2", name: "Bob", email: "bob@example.com" }],
]);
async findById(id: string) {
return this.users.get(id) ?? null;
}
async listAll() {
return Array.from(this.users.values());
}
async create(name: string, email: string) {
const id = String(this.users.size + 1);
const user = { id, name, email };
this.users.set(id, user);
return user;
}
}
// --- 2. Schemas ---
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(6),
});
const createUserSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
});
// --- 3. Controllers ---
export class LoginController extends Controller {
static schema = { body: loginSchema };
constructor(private readonly auth: Auth) {
super();
}
async handle(ctx: RequestContext) {
const { email } = ctx.valid<z.infer<typeof loginSchema>>("body");
// Issue token for valid credentials
const token = await this.auth.generateToken({ id: "1", email, role: "member" });
return this.success({ token });
}
}
export class ListUsersController extends Controller {
constructor(private readonly users: UserService) {
super();
}
async handle() {
return this.success(await this.users.listAll());
}
}
export class CreateUserController extends Controller {
static schema = { body: createUserSchema };
constructor(private readonly users: UserService) {
super();
}
async handle(ctx: RequestContext) {
const { name, email } = ctx.valid<z.infer<typeof createUserSchema>>("body");
const created = await this.users.create(name, email);
return this.created(created);
}
}
// --- 4. Application Bootstrap ---
export const app = new Application({ port: 3000 });
// Global Auth & Services
export const auth = new Auth({ secret: "super-secure-production-secret-key-32ch" });
app.singleton(Auth, () => auth);
app.singleton(UserService);
// Global Middleware
app.use(new CorsMiddleware({ origins: ["*"], credentials: true }));
app.use(createRateLimitMiddleware({ windowMs: 60_000, maxRequests: 100 }));
app.middleware("auth", createAuthMiddleware(auth));
// Route Groups
app.group("/api/v1", (router) => {
// Public routes
router.post("/auth/login", LoginController);
// Protected routes
router.group("/users", (r) => {
r.get("/", ListUsersController);
r.post("/", CreateUserController);
}, { middleware: ["auth"] });
});
// Expose OpenAPI & Interactive UI
app.exposeDocs("/docs", "/openapi.json");
// Start server when run directly
if (import.meta.main) {
await app.listen();
}
3. Testing with Bun Test¶
// tests/app.test.ts
import { describe, it, expect } from "bun:test";
import { app } from "../src/app";
import { createTestToken } from "katal/testing";
describe("Simple App E2E", () => {
it("rejects unauthorized access to /api/v1/users", async () => {
const res = await app.handle(new Request("http://localhost/api/v1/users"));
expect(res.status).toBe(401);
});
it("allows access with valid JWT token", async () => {
const token = await createTestToken({ id: "1", role: "member" }, "super-secure-production-secret-key-32ch");
const res = await app.handle(new Request("http://localhost/api/v1/users", {
headers: { Authorization: `Bearer ${token}` },
}));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.data.length).toBeGreaterThan(0);
});
});
4. Run Locally¶
bun run src/app.ts
Open http://localhost:3000/docs in your browser to interact with the OpenAPI Scalar interface!