S42-Core RouteControllers Class
- ROUTE CONTROLLERS
- Overview
- Purpose
- Key Features
- Methods
processAllControllers()setServer(server: Server)listen(port: number)checkRoute(route: string): RouteCheckResultaddHeader(header: string, value: string)setHeaders()getHeadersToSend(): { [key: string]: string }setResponseHeaders()clearAllHeaders()getQueryParams(url: string): { [key: string]: string }getRequestObject(req: IncomingMessage): Promise<TypeRequestInternalObject>getResponseObject(res: ServerResponse): TypeResponseInternalObjectnotFound(res: ServerResponse, message?: string)serverError(res: ServerResponse, message?: string)addGlobal(callback: (req: TypeRequest, res: ServerResponse, next?: (req: TypeRequest, res: ServerResponse) => void) => void)getCallback(): TypeReturnCallbackgetInstance(controllers: Controller[])
- Controller Parameters
- Use Cases
RouteControllers Documentation
The RouteControllers class is part of the s42-core package and is designed to manage and route HTTP requests efficiently. It works seamlessly with the Controller class to handle routes, middlewares, and HTTP methods dynamically.
Using RouteControllers without the Controller class does not make sense, as it relies entirely on Controller instances to define and manage the routing logic.
Purpose
The RouteControllers class processes a collection of Controller instances and maps their paths and methods to appropriate callbacks. It evaluates whether an incoming request matches a defined route, enabling dynamic routing with support for:
- Wildcard paths (e.g.,
*for any path). - Dynamic parameters (e.g.,
/users/:userId). - Wildcard HTTP methods (e.g.,
'*'for any method).
Installation
Install the s42-core package to use RouteControllers:
npm install s42-coreUsage
Importing and Defining Controllers
To use RouteControllers, you must define routes using the Controller class.
import { Controller, RouteControllers, Server } from 's42-core';
async function main() { const server = new Server();
// Define controllers const controllerTest = new Controller('GET', '/test', async (req, res) => { console.info('URL:', req.url); return res.json({ message: 'Hello World!' }); });
const controllerWithParams = new Controller('GET', '/users/:userId', async (req, res) => { console.info('Params:', req.params); return res.json({ userId: req.params.userId }); });
const wildcardController = new Controller('*', '*', async (req, res) => { console.info('All paths and methods'); return res.text('Resource not found'); });
// Add middleware to a controller controllerTest.use(async (req) => { req.extraInfo = 'middleware data'; });
// Create RouteControllers with controllers const routeControllers = new RouteControllers([ controllerTest, controllerWithParams, wildcardController, ]);
// Start the server await server.start({ port: 3000, RouteControllers: routeControllers, });
console.info('Server is running on:', server.getURL());}
main();Key Methods
constructor(controllers: Controller[])
Initializes the RouteControllers instance with an array of Controller instances.
Parameters:
controllers: An array ofControllerinstances defining the routes.
getCallback(): (req: Request) => Promise<Response>
Returns a callback function to handle incoming requests. This callback determines if a route exists and invokes the appropriate middleware chain.
checkRoute(route: string): RouteCheckResult
Evaluates if a given route exists in the registered controllers. It supports:
- Wildcard methods (
'*'). - Wildcard paths (
'*'). - Dynamic parameters (e.g.,
:userId).
Example Result:
{ exists: true, params: { userId: '123' }, key: 'GET:/users/:userId'}Features
- Dynamic Routing: Handles static paths, dynamic parameters, and wildcard routes with ease.
- Middleware Support: Integrates middleware into
Controllerinstances for pre-processing requests. - Efficient Mapping: Builds an internal cache for quick lookup of routes and callbacks.
- Error Handling: Returns appropriate
404or500responses for unmatched routes or internal errors. - Flexible Integration: Works seamlessly with the
Serverclass froms42-core.
Example Output
1. Defined Routes
-
Route:
GET /test- Response:
{ "message": "Hello World!" }
- Response:
-
Route:
GET /users/123- Response:
{ "userId": "123" }
- Response:
-
Route:
POST /unknown- Response:
"Resource not found"
- Response:
Advantages
- Simplifies Routing: Automatically maps controllers to routes.
- Supports Wildcards: Flexible routing with
'*'for methods and paths. - Error Resilience: Ensures proper handling of unmatched routes and exceptions.
- Middleware Integration: Allows layered logic for requests.
License
This project is licensed under the MIT License. See the LICENSE file for details.