Controllers
Organize your request handling logic into reusable controller classes. CanxJS controllers use TypeScript decorators for clean, expressive route definitions.
Class-Based
Organize related routes into clean, reusable controller classes
Decorators
Use @Get, @Post, @Put, @Delete decorators for clean routing
Middleware
Apply middleware at controller or method level with @Middleware
Base Controller
Built-in helper methods for common tasks like JSON, redirect, body
Creating a Controller
Create a controller class that extends BaseControllerand use decorators to define routes. The @Controller decorator sets the base path prefix for all routes in the controller.
1import { BaseController, Get, Post, Put, Delete, Controller } from "canxjs";23@Controller("/users")4export class UserController extends BaseController {56@Get("/")7async index() {8const users = await User.all();9return this.json(users);10}1112@Get("/:id")13async show() {14const user = await User.find(this.param("id"));1516if (!user) {17return this.json({ error: "User not found" }, 404);18}1920return this.json(user);21}2223@Post("/")24async store() {25const data = await this.body<CreateUserDto>();26const user = await User.create(data);27return this.json(user, 201);28}2930@Put("/:id")31async update() {32const id = this.param("id");33const data = await this.body<UpdateUserDto>();34const user = await User.update(id, data);35return this.json(user);36}3738@Delete("/:id")39async destroy() {40const id = this.param("id");41await User.delete(id);42return this.json({ deleted: true });43}44}
Route Decorators
| Decorator | HTTP Method | Usage |
|---|---|---|
| @Get(path) | GET | Retrieve resources |
| @Post(path) | POST | Create new resources |
| @Put(path) | PUT | Update entire resources |
| @Patch(path) | PATCH | Partial updates |
| @Delete(path) | DELETE | Remove resources |
Controller Middleware
Apply middleware to the entire controller or specific methods using the @Middleware decorator.
1import { Controller, Get, Post, Middleware } from "canxjs";2import { authMiddleware, adminMiddleware } from "./middlewares";34// Apply middleware to entire controller5@Controller("/admin")6@Middleware(authMiddleware, adminMiddleware)7export class AdminController extends BaseController {89@Get("/dashboard")10async dashboard() {11const stats = await this.getDashboardStats();12return this.json(stats);13}1415// Apply additional middleware to specific method16@Get("/secrets")17@Middleware(superAdminMiddleware)18async secrets() {19return this.json({ secret: "classified" });20}21}
BaseController Methods
The BaseController class provides helpful methods for common operations:
| Method | Description |
|---|---|
| this.json(data, status?) | Send JSON response |
| this.html(content, status?) | Send HTML response |
| this.redirect(url, status?) | Redirect to URL |
| this.param(key) | Get route parameter |
| this.query(key) | Get query parameter |
| this.body<T>() | Get typed request body |
| this.header(name) | Get request header |
| this.cookie(name) | Get cookie value |
| this.setCookie(name, value, options?) | Set cookie |
1export class ArticleController extends BaseController {23@Get("/:id")4async show() {5// Access route parameters6const id = this.param("id");78// Access query parameters9const includeComments = this.query("include") === "comments";1011// Access request headers12const userAgent = this.header("user-agent");1314// Access cookies15const sessionId = this.cookie("session_id");1617const article = await Article.find(id);1819// Send JSON response20return this.json(article);21}2223@Post("/")24async store() {25// Get request body with type26const data = await this.body<CreateArticleDto>();2728const article = await Article.create(data);2930// Set cookie31this.setCookie("last_article", article.id, {32httpOnly: true,33maxAge: 8640034});3536return this.json(article, 201);37}3839@Get("/:id/edit")40async edit() {41const id = this.param("id");42const article = await Article.find(id);4344if (!article) {45// Redirect to another page46return this.redirect("/articles");47}4849// Render HTML50return this.html(`<h1>Edit: ${article.title}</h1>`);51}52}
Registering Controllers
Register controllers with your application using the app.controller() method.
1import { createApp } from "canxjs";2import { UserController } from "./controllers/UserController";3import { ArticleController } from "./controllers/ArticleController";45const app = createApp({ port: 3000 });67// Register controllers8app.controller(UserController);9app.controller(ArticleController);1011app.listen();
Resource Controllers
Generate CRUD operations automatically with resource controllers. Use app.resource() to register standard REST routes.
1import { BaseController } from "canxjs";23// Resource controller with CRUD operations4export class PostController extends BaseController {5// GET /posts6async index() {7return this.json(await Post.all());8}910// GET /posts/:id11async show() {12return this.json(await Post.find(this.param("id")));13}1415// POST /posts16async store() {17const data = await this.body();18return this.json(await Post.create(data), 201);19}2021// PUT /posts/:id22async update() {23const id = this.param("id");24const data = await this.body();25return this.json(await Post.update(id, data));26}2728// DELETE /posts/:id29async destroy() {30await Post.delete(this.param("id"));31return this.json({ success: true });32}33}3435// Register as resource route36app.resource("/posts", PostController);