25.0.0-beta.3 • Published 6 months ago
@contextjs/webserver-middleware-controllers v25.0.0-beta.3
@contextjs/webserver-middleware-controllers
Controllers middleware for the ContextJS webserver.
Installation
npm i @contextjs/webserver-middleware-controllersOverview
This package provides attribute-based routing support for the ContextJS webserver. It introduces a controller and verb decorator model, allowing you to build organized, testable route handlers similar to established MVC patterns.
Features
- Attribute-based route mapping using
@Controller,@Get,@Post,@Put, and@Delete - Auto-discovery of compiled
.jsor.mjscontrollers - Customizable default controller and action fallbacks
- Integration via
.useControllers()onWebServerOptions
Usage
import "@contextjs/di";
import "@contextjs/webserver";
import "@contextjs/webserver-middleware-controllers";
import { Application } from "@contextjs/system";
import { WebServerOptions } from "@contextjs/webserver";
import { Controller, Get } from "@contextjs/webserver-middleware-controllers";
interface ILoggerService {
log(message: string): void;
}
class LoggerService implements ILoggerService {
log(message: string): void {
console.log(message);
}
}
@Controller()
class HomeController {
private readonly loggerService: ILoggerService;
public constructor(loggerService: ILoggerService) {
this.loggerService = loggerService;
}
@Get("index")
public async index() {
this.loggerService.log("HomeController index method called");
return "Home";
}
}
const application = new Application();
application.useDependencyInjection();
application.services.addTransient<ILoggerService, LoggerService>();
application.useWebServer((options: WebServerOptions) => {
options.onEvent = (event) => console.log(event.type, event.detail);
options.useControllers();
});
await application.runAsync();Requests to /home/index will be routed to the index() method of HomeController.
Configuration
You can optionally customize the default controller and action name:
application.useWebServer((options: WebServerOptions) => {
options.onEvent = (event) => console.log(event.type, event.detail);
options.useControllers(controllerOptions => {
controllerOptions.defaultController = "about";
controllerOptions.defaultAction = "index";
});
});Controller Auto-Discovery
Controllers are discovered automatically from the outDir specified in your tsconfig.json. You must compile your controllers to .js or .mjs files.
API Reference
For detailed API documentation, please refer to the API Reference.
25.0.0-beta.3
6 months ago
25.0.0-beta.2
6 months ago
25.0.0-beta.1
6 months ago
0.5.3-alpha.1
6 months ago
0.5.2-alpha.1
6 months ago