# Express-Router

Express-Router is a high-performance routing system for Express.js based on the proven architecture of insitu-js. It provides an optimized routing solution with support for parametrized routes, JSON route files loading, directory-based route loading, and an extensible hooks system.

## Key Features

- **High-Performance Routing**: Uses indexes and regex caching for optimized route matching
- **Parametrized Routes**: Full support for dynamic routes like `/users/:id`
- **JSON Route Loading**: Define routes in JSON configuration files
- **Directory-Based Loading**: Load multiple route files from a directory
- **Hook System**: Extensible via the [express-hooked](../hooked/) hook system
- **Express Middleware**: Fully compatible with Express.js architecture
- **Duplicate Route Detection**: Alerts when duplicate routes are defined
- **Static Route Support**: Serve static files from directories

## Installation

```bash
npm install express-router express-hooked
```

## Quick Start

### 1. Basic Setup

```javascript
const express = require('express');
const ExpressRouterIntegration = require('express-router');

const app = express();
const routerIntegration = new ExpressRouterIntegration();

// Add routes directly
routerIntegration
  .get('/api/hello', (req, res) => {
    res.json({ message: 'Hello from Express-Router!' });
  })
  .get('/api/users/:id', (req, res) => {
    const userId = req.params.id;
    res.json({ message: `User ID: ${userId}` });
  });

// Apply router to Express app
routerIntegration.applyToApp(app);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
```

### 2. JSON Route Files

Define routes in JSON files:

```json
[
  {
    "method": "GET",
    "path": "/api/users",
    "controller": "./controllers/usersController",
    "handler": "listUsers",
    "contentType": "application/json"
  },
  {
    "method": "GET",
    "path": "/api/users/:id",
    "controller": "./controllers/usersController",
    "handler": "getUser",
    "contentType": "application/json"
  }
]
```

### 3. Directory-Based Loading

Load routes from multiple JSON files in a directory:

```javascript
const RouteDirectoryLoader = require('express-router/RouteDirectoryLoader');

const routeDirectoryLoader = new RouteDirectoryLoader();

// Load routes from directory containing multiple JSON files
routeDirectoryLoader.loadRoutesFromDirectory(routerIntegration, './routes')
  .then(routes => {
    console.log(`${routes.length} routes loaded from directory`);
  });
```

## Advanced Features

### Hook System

The routing system integrates with the [express-hooked](../hooked/) hook system, allowing customization through extension points.

#### Available Hooks

- `pre_route_load`: Executed before loading routes from a file
- `post_route_load`: Executed after loading routes from a file
- `route_added`: Executed after a route is added
- `before_route_processing`: Executed before processing any route
- `route_matched`: Executed when a matching route is found
- `before_route_handler`: Executed before executing a route handler
- `after_route_handler`: Executed after executing a route handler
- `route_handler_error`: Executed when a route handler error occurs

#### Custom Hook Example

```javascript
// Register a hook to execute logic before processing any route
routerIntegration.addHook('before_route_processing', (req, res) => {
  console.log(`Processing route: ${req.method} ${req.url}`);
});

// Register a hook when a matching route is found
routerIntegration.addHook('route_matched', (matchedRoute, req, res) => {
  console.log(`Route found: ${matchedRoute.route.path}`);
  console.log(`Parameters:`, matchedRoute.params);
});
```

## Performance Benefits

Express-Router implements several optimizations that make it faster than traditional Express routing:

- **Regex Caching**: Regular expressions for parametrized routes are cached to avoid recompilation
- **Route Indexing**: Routes are indexed by method and path segments for faster lookup
- **Pre-filtering**: Candidate routes are pre-filtered using indexes before detailed matching
- **Hierarchical Search**: Multiple search strategies (exact, parametrized, prefix) with optimal ordering

## Why Choose Express-Router?

- **Battle-tested Architecture**: Based on the proven insitu-js routing system used in production
- **High Performance**: Optimized algorithms for route matching
- **Flexible Loading**: Support for both file-based and directory-based route definitions
- **Extensible**: Rich hook system for customization
- **Developer Friendly**: Clean API and comprehensive documentation
- **Production Ready**: Built with reliability and scalability in mind

## License

Apache 2.0