Controllers

Controllers are responsible for handling HTTP and WebSocket requests in your application. They serve as the entry point for external requests and act as the bridge between the transport layer and your business logic.

Purpose

Controllers MUST only perform these specific tasks:

  1. Validate transport layer input - Verify authentication, authorization, and input format

  2. Call logic components - Delegate business logic to appropriate logic components

  3. Transform input - Convert request data into parameters for logic component calls

  4. Handle errors - Catch and properly respond to errors from logic components

Location

All controllers MUST be placed under the /src/controllers directory and be named in reference to the action they perform.

src/
└── controllers/
    ├── users/
    │   ├── get-user.ts
    │   ├── create-user.ts
    │   └── update-user.ts
    ├── content/
    │   ├── publish-content.ts
    │   └── delete-content.ts
    └── health.ts

Controller Structure

Basic HTTP Handler

POST Request Handler

Query Parameters Handler

Input Requirements

All input keys received through controllers (JSON body, query parameters, URL parameters, headers, etc.) MUST be in lowercase to prevent casing issues when processing data.

Multi-word Parameters

Multi-word parameters MUST be defined using snake_case.

Example

Error Handling

Standard Error Responses

Controllers should return consistent error response formats:

Error Mapping

Map domain errors to appropriate HTTP status codes:

Authentication and Authorization

Authentication Check

Authorization Check

Best Practices

1. Keep Controllers Thin

Controllers should be thin wrappers around logic components:

2. Validate Early

Validate and fail fast:

3. Use Type Safety

Leverage TypeScript for type safety:

4. Log Appropriately

Log important events and errors:

Testing Controllers

See the Testing Services (WKC) documentation for integration testing guidance.

Last updated