Skip to content

HttpService

This file defines the HttpService class, the core HTTP server and routing engine for the @sodacore/core framework. It handles server initialization, controller and middleware registration, request dispatching, context creation, SSE support, WebSocket event listeners, and response transformation.


Features

  • Server Initialization: Sets up and starts a Bun HTTP server with configurable host and port.
  • Controller & Middleware Registration: Discovers and registers all controllers and middleware from the DI registry.
  • Routing: Builds a routing table from controller metadata, supporting all HTTP methods and paths.
  • Request Handling: Creates an HttpContext for each request, runs middleware, and dispatches to the correct controller method.
  • Parameter Injection: Supports injection of request, server, params, query, headers, cookies, body, URL, and method into controller methods.
  • Response Transformation: Applies transformers to controller responses before sending them to the client.
  • SSE Support: Handles Server-Sent Events (SSE) requests and manages SSE connections.
  • WebSocket Event Listeners: Allows attaching and removing listeners for WebSocket events (open, close, drain, message).
  • Graceful Shutdown: Stops the server and clears all SSE connections on shutdown.

Usage

The HttpService is registered and started automatically by the Sodacore HTTP plugin. It is not typically instantiated directly.

typescript
import HttpService from './service/http';

const httpService = new HttpService();
await httpService.init();
await httpService.start();
// ... later
await httpService.stop();

API

Lifecycle Methods

  • async init(): Promise<void> Initializes the service, discovers controllers and middleware, and builds the routing table.

  • async start(): Promise<void> Starts the Bun HTTP server and begins listening for requests.

  • async stop(): Promise<void> Stops the server and clears all SSE connections.

WebSocket Listener Management

  • addListener(event: IWebSocketEvents, listener: IWebSocketEventListener): void Adds a listener for a specific WebSocket event.

  • removeListener(event: IWebSocketEvents, listener: IWebSocketEventListener): void Removes a listener for a specific WebSocket event.

Configuration

  • setConfig(key: string, value: any, forWs = false): void Sets a configuration value for the HTTP or WebSocket server.

Internal Methods

  • private setupServerConfig(): void Configures the Bun server, including fetch and WebSocket handlers.

  • private async handleRequest(request: Request, server: Server): Promise<Response> Creates context, runs middleware, and dispatches the request.

  • private async dispatch(context: HttpContext): Promise<Response> Matches the request to a route, injects parameters, runs the controller method, applies transformers, and returns a response.

  • private handleSseRequest(context: HttpContext): Response Handles SSE upgrade requests and returns an SSE response.

  • private async getMethodArgument(index: number, args: IControllerMethodArgItem[], context: HttpContext, params: Record<string, any>): Promise<any> Resolves and injects method arguments based on parameter decorators.

  • private asNumber(value: any): any Converts a value to a number if possible, otherwise returns the original value.


How It Works

  1. Initialization:

    • Discovers all controllers and middleware from the DI registry.
    • Builds a routing table from controller metadata, associating HTTP methods and paths with controller methods and transformers.
  2. Request Handling:

    • For each incoming request, creates an HttpContext.
    • Runs all registered middleware; if any returns a Response or false, halts further processing.
    • Dispatches the request to the appropriate controller method, injecting parameters as needed.
    • Applies any attached transformers to the result.
    • Converts the result to a standardized Response object and returns it.
  3. SSE and WebSocket:

    • Handles SSE upgrade requests and manages connections via SseConnectionsProvider.
    • Supports adding/removing WebSocket event listeners for real-time communication.
  4. Shutdown:

    • Stops the server and ensures all SSE connections are closed.

Notes

  • This service is designed to be used as the main HTTP entry point in a Sodacore application.
  • Supports advanced features like middleware, response transformation, SSE, and WebSocket out of the box.
  • Uses Bun's native HTTP and WebSocket APIs for high performance.
  • All controller and middleware discovery is automatic via the Sodacore DI registry.

Released under the Apache-2.0 License.