# Express-Hooked

Express-Hooked is a powerful extension for Express.js that brings a comprehensive hooks and filters system to your applications. Inspired by WordPress hooks system, it allows developers to extend functionality at various points in the request lifecycle without modifying core code.

## Why Choose Express-Hooked?

- **Flexible Architecture**: Hook into request processing at multiple stages
- **Non-Intrusive**: Extend functionality without modifying existing code
- **Priority System**: Control execution order with priority levels
- **Namespace Support**: Organize hooks with namespaces for better maintainability
- **Easy Integration**: Simple setup with minimal configuration

## Installation

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

## Quick Start

```javascript
const express = require('express');
const ExpressHooked = require('express-hooked');

const app = express();
const port = 3000;

// Initialize ExpressHooked
const expressHooks = new ExpressHooked(app);

// Register an action hook
expressHooks.addAction('request_started', (req, res, next) => {
  console.log(`Request received: ${req.method} ${req.url}`);
  next();
});

// Register a filter hook
expressHooks.addFilter('modify_response_data', (data) => {
  return {
    ...data,
    processedBy: 'ExpressHooked',
    timestamp: new Date().toISOString()
  };
});

// Example route using filters
app.get('/', (req, res) => {
  let responseData = { message: 'Hello World!' };
  responseData = expressHooks.applyFilters('modify_response_data', responseData);
  
  res.json(responseData);
});

// Initialize hooks integration
expressHooks.init();

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
```

## Key Features

### Actions
Actions allow you to execute code at specific points without modifying data:

```javascript
expressHooks.addAction('request_started', (req, res, next) => {
  // Do something when request starts
  next();
});
```

### Filters
Filters allow you to modify data flowing through your application:

```javascript
expressHooks.addFilter('modify_response_data', (data) => {
  // Modify and return the data
  return { ...data, customField: 'value' };
});
```

### Priority System
Control execution order with priority levels (lower numbers execute first):

```javascript
// This executes first (higher priority)
expressHooks.addAction('request_started', callback, 5);

// This executes later (lower priority)
expressHooks.addAction('request_started', callback, 15);
```

### Namespaces
Organize your hooks with namespaces:

```javascript
// Register hook with namespace
expressHooks.addAction('myplugin::before_request', callback);

// Execute namespaced hook
expressHooks.doAction('myplugin::before_request', req, res);
```

### Advanced Methods

#### Removing Hooks and Filters
You can remove specific hooks or filters using the following methods:

```javascript
// Remove a specific action
expressHooks.removeAction('request_started', callback);

// Remove an action by identifier
expressHooks.removeAction('request_started', 'my-action-id');

// Remove all actions for a hook
expressHooks.removeAllActions('request_started');

// Remove a specific filter
expressHooks.removeFilter('modify_response_data', callback);

// Remove a filter by identifier
expressHooks.removeFilter('modify_response_data', 'my-filter-id');

// Remove all filters for a hook
expressHooks.removeAllFilters('modify_response_data');
```

#### Checking for Hooks and Filters
Check if hooks or filters exist for a specific hook name:

```javascript
// Check if an action exists
const hasAction = expressHooks.hasAction('request_started');

// Check if a filter exists
const hasFilter = expressHooks.hasFilter('modify_response_data');
```

#### Counting Hooks and Filters
Get the number of registered hooks or filters for a specific hook name:

```javascript
// Count actions for a hook
const actionCount = expressHooks.actionsCount('request_started');

// Count filters for a hook
const filterCount = expressHooks.filtersCount('modify_response_data');
```

#### Asynchronous Hooks and Filters
Execute hooks and filters asynchronously:

```javascript
// Execute actions asynchronously
await expressHooks.doActionAsync('request_started', req, res, next);

// Apply filters asynchronously
const filteredData = await expressHooks.applyFiltersAsync('modify_response_data', data);
```

### Additional Parameters
When registering hooks, you can specify additional parameters:

```javascript
// acceptedArgs: Number of arguments the callback accepts
expressHooks.addAction('request_started', callback, priority, acceptedArgs);

// identifier: Optional identifier for the callback (useful for removal)
expressHooks.addAction('request_started', callback, priority, acceptedArgs, 'my-action-id');
```

### Error Handling
Errors within hooks are caught and logged to prevent crashing the application:

```javascript
expressHooks.addAction('request_started', (req, res, next) => {
  // If an error occurs here, it will be caught and logged
  problematicFunction();
  next();
});
```

### Route-Specific Hooks
Register hooks for specific routes:

```javascript
// Register a hook to run before a specific route
expressHooks.addRouteHook('/api/users', 'before', (req, res, next) => {
  console.log('Before /api/users route');
  next();
});

// Register a hook to run after a specific route
expressHooks.addRouteHook('/api/users', 'after', (req, res, data) => {
  console.log('After /api/users route');
});
```

### Extending Express Methods
Extend Express methods with custom functionality:

```javascript
// Extend an Express method with custom functionality
expressHooks.extendExpressMethod('use', (originalUse) => {
  return function(path, ...middlewares) {
    // Custom logic before calling the original method
    console.log(`Registering middleware for path: ${path}`);
    
    // Call the original method
    return originalUse.call(this, path, ...middlewares);
  };
});
```

### Version Compatibility
The current version of Express-Hooked follows semantic versioning. Breaking changes will be documented in the changelog.

## Use Cases

- **Authentication & Authorization**: Hook into request processing to validate credentials
- **Logging & Analytics**: Track requests, responses, and performance metrics
- **Caching**: Implement caching strategies at different levels
- **API Transformation**: Modify API responses before sending to clients
- **Error Handling**: Centralized error handling with custom logic
- **Rate Limiting**: Implement rate limiting based on custom criteria

## Contributing

We welcome contributions! Please see our contributing guidelines for more information.

## License

Apache 2.0

Repository: https://gitlab.com/bytedogssyndicate1/express-hooked