Controller Setup
Noblex lets you define controllers with decorators that organize your routes cleanly and add middleware on both controller and route levels.
Example: src/modules/wallets/wallets.controller.ts
import type { Request, Response, NextFunction } from "noblex";
import { Controller, Route, Get } from "noblex";
@Controller("/wallets", [
(req: Request, res: Response, next: NextFunction) => {
console.log("controller method sync");
next();
},
])
class WalletController /* extends WalletMethods*/ {
@Get("/sync",
(req: Request, res: Response, next: NextFunction) => {
console.log("middleware method sync");
next();
},
)
async syncWalletHandler(req: Request) {
console.log("sync method called");
const data = { a: 22 }; // await super.syncWallet();
return data;
}
}
export default WalletController;
What’s happening here?
-
@Controller("/wallets", [...])
Defines the base route/wallets
and attaches controller-level middleware executed on every route inside this controller. -
@Get("/sync", [...])
Defines a GET endpoint/wallets/sync
with optional route-level middleware. -
Middleware functions receive the usual
req
,res
, andnext
parameters and run before the handler. -
The handler method (
syncWalletHandler
) is async and returns data directly — Noblex handles sending the JSON response automatically.
Middleware Usage Styles with Example
You can apply middleware in two different ways in Noblex controllers:
-
@Controller("/wallets", mid1, mid2, ...)
This style appends middleware to the existing dynamic middleware stack. -
@Controller("/wallets", [mid1, mid2, ...])
This style replaces (overwrites) the dynamic middleware with the given array.
The same applies to class methods:
-
Middleware declared on class methods appends to controller middleware by default.
-
Middleware passed as an array to methods replaces controller and dynamic middleware for that route.
Example: Authorization Middleware
Suppose you set an authorization middleware globally on the controller:
@Controller("/users")
class UsersController {
@Post("/login", []) // This route removes the auth middleware override
async login(req: Request) {
// Public login endpoint, no auth required
}
@Get("/profile")
async profile(req: Request) {
// Requires auth because middleware is appended from controller
}
}
💡 Tip:
You can also set your auth middleware in the app’s dynamic middleware array, making it accessible across the whole application or selectively override it per controller or route.
This is usually the best approach unless you have many public APIs that should bypass the auth middleware. In that case, controlling middleware per controller or route can be cleaner. Important: Always import all your controllers before you create and runnew App()
to ensure routes and middleware are properly registered.