Plugin System

Novaxjs2's plugin system allows you to extend the framework with custom functionality, methods, routes, and middleware.

Creating a Plugin

Plugins are functions that receive a context object with methods to extend the framework:

function myPlugin(context, options) {
  const { addMethod, addRoute, addMiddleware, setConfig, getConfig } = context;
  
  // Add new methods to the app instance
  addMethod('greet', function(name) {
    return `Hello ${name}!`;
  });
  
  // Add custom routes
  addRoute('get', '/plugin-route', (req, res) => {
    return 'This route was added by plugin';
  });
  
  // Add middleware
  addMiddleware((req, res, next) => {
    console.log('Plugin middleware executed');
    next();
  });
  
  // Store configuration
  setConfig('apiKey', options.apiKey);
  
  // Retrieve configuration later
  const apiKey = getConfig('apiKey');
  
  // You can also return values that will be available on the app instance
  return {
    utilityFunction: () => 'This is a utility function'
  };
}

Using a Plugin

const Nova = require('novaxjs2');
const app = new Nova();

// Use the plugin with options
app.usePlugin(myPlugin, { 
  apiKey: 'your-api-key-here',
  otherSetting: 'value' 
});

// Now you can use plugin methods
app.get('/', (req, res) => {
  const greeting = app.greet('World'); // From plugin
  const utility = app.utilityFunction(); // From plugin return value
  
  return res.send(`${greeting} - ${utility}`);
});

// Plugin routes are automatically registered
// Access: GET /plugin-route

Plugin Context Methods

MethodDescriptionParameters
addMethod(name, fn)Adds a method to the app instancename: string, fn: function
addRoute(method, path, handler)Adds a route with the specified HTTP methodmethod: string, path: string, handler: function
addMiddleware(fn)Adds application-level middlewarefn: function(req, res, next)
addErrorMiddleware(fn)Adds error handling middlewarefn: function(err, req, res, next)
setConfig(key, value)Stores configuration valueskey: string, value: any
getConfig(key)Retrieves configuration valueskey: string

Complete Plugin Example

// plugins/auth-plugin.js
function authPlugin(context, options) {
  const { addMethod, addMiddleware, setConfig } = context;
  
  // Store configuration
  setConfig('jwtSecret', options.jwtSecret);
  
  // Add authentication middleware
  addMiddleware((req, res, next) => {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    
    try {
      // Verify token (pseudo-code)
      req.user = verifyToken(token, options.jwtSecret);
      next();
    } catch (err) {
      return res.status(401).json({ error: 'Invalid token' });
    }
  });
  
  // Add auth utility methods
  addMethod('requireAuth', (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    next();
  });
  
  addMethod('requireRole', (role) => {
    return (req, res, next) => {
      if (!req.user || req.user.role !== role) {
        return res.status(403).json({ error: 'Insufficient permissions' });
      }
      next();
    };
  });
  
  return {
    generateToken: (userData) => {
      // Token generation logic
      return signToken(userData, options.jwtSecret);
    }
  };
}

// Using the auth plugin
const Nova = require('novaxjs2');
const app = new Nova();

app.usePlugin(authPlugin, {
  jwtSecret: 'your-secret-key'
});

// Protected route using plugin methods
app.get('/admin', 
  app.requireAuth,
  app.requireRole('admin'),
  (req, res) => {
    return res.json({ message: 'Welcome admin!', user: req.user });
  }
);

Best Practices for Plugins