S42-Core Controller Class
- Controller Documentation
Controller Documentation
The Controller
class is part of the s42-core
package and provides an intuitive and flexible way to define endpoints for HTTP requests. It supports dynamic routing, middleware chaining, and multiple HTTP methods for each path.
This class is designed to work seamlessly with the RouteControllers
class to manage application routes efficiently.
Purpose
The Controller
class:
- Simplifies defining HTTP endpoints.
- Supports middlewares for processing requests.
- Handles multiple HTTP methods for a single endpoint.
- Allows dynamic parameterized routes.
Installation
Install the s42-core
package:
Usage
Basic Example
Adding Middlewares
You can chain multiple middlewares for preprocessing the request. Middlewares are executed in order and can optionally return a Response
. If a middleware returns undefined
, the next middleware in the chain is executed.
Handling Multiple Methods
You can add multiple HTTP methods for a single controller.
This allows the same path /hello
to handle GET
, POST
, and DELETE
requests.
Dynamic Parameters
Define dynamic routes with parameters:
The req.params
object contains the dynamic parameters parsed from the URL.
Key Methods
Constructor
method
: The HTTP method for the route (e.g.,GET
,POST
).path
: The route path (e.g.,/users/:userId
).callback
: The primary middleware for handling the request.
getPath(): string
Returns the path associated with the controller.
getMethods(): TYPE_HTTP_METHOD[]
Returns an array of HTTP methods supported by the controller.
use(callback: Middleware): this
Adds a middleware to the controller. Middlewares are executed in the order they are added.
HTTP Methods
These methods allow adding HTTP methods to the controller:
get()
: AddsGET
method.post()
: AddsPOST
method.delete()
: AddsDELETE
method.put()
: AddsPUT
method.patch()
: AddsPATCH
method.options()
: AddsOPTIONS
method.update()
: AddsUPDATE
method.
getCallback(): (req: Request, res: Res) => Promise<Response>
Returns a callback function that handles the incoming request. The function executes the middleware chain and returns a Response
.
Example Integration with RouteControllers
The Controller
class is designed to work with RouteControllers
. Here’s an example:
Features
- Dynamic Routing: Supports static, dynamic, and wildcard routes.
- Middleware Support: Enables layered request processing.
- Flexible Methods: Easily handle multiple HTTP methods for a single path.
- Integration-Ready: Designed to work with
RouteControllers
for efficient routing.
Advantages
- Modular: Allows defining endpoints as self-contained modules.
- Chainable: Add multiple methods and middlewares fluently.
- Error Handling: Includes robust error handling for middleware chains.
- Dynamic Parameters: Supports parameterized routes for flexible routing.
License
This project is licensed under the MIT License. See the LICENSE file for details.