1.0.0 • Published 4 months ago

flow-server-plugin-router-class-method v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Flow Server Plugin: RouterClassMethod

A plugin for Flow Server Framework that provides class-based service method routing, similar to the old Flow Framework's services.js router.

Features

  • Dynamic loading of service classes
  • Automatic routing of service methods
  • JSON request/response handling
  • Error handling with customizable responses
  • Follows the "pif paf hopla" philosophy:
    • Pif: Auto-discovery of service classes
    • Paf: Auto-configuration of routes
    • Hopla: Auto-adaptation to different environments

Installation

npm install flow-server-plugin-routerClassMethod

Usage

1. Register the plugin with your Flow Server application

// In your app.js or index.js
const { createFlow } = require('flow-server-framework');
const createRouterClassMethodPlugin = require('flow-server-plugin-routerClassMethod');

// Create Flow instance
const flow = createFlow();

// Register HTTP engine
const { HttpEngine } = require('flow-server-framework');
flow.registerEngine('http', new HttpEngine({ port: 3000 }));

// Register RouterClassMethod plugin
const routerPlugin = createRouterClassMethodPlugin({
  servicesPath: 'services',  // Path to your service classes
  baseRoute: '/api/services' // Base route for all service endpoints
});

// Initialize and start the application
flow.init()
  .then(() => flow.start())
  .catch(err => console.error('Failed to start:', err));

2. Create service classes

Create service classes in your services directory with static methods:

// services/Example.js
class Example {
  static async testMethod(params) {
    return {
      received: params,
      timestamp: new Date(),
      message: "This service was loaded dynamically!"
    };
  }

  static async calculate(params) {
    const { x = 0, y = 0 } = params;
    return {
      x: Number(x),
      y: Number(y),
      sum: Number(x) + Number(y),
      product: Number(x) * Number(y),
      timestamp: new Date()
    };
  }
}

module.exports = Example;

3. Access your services via HTTP

You can now access your service methods via HTTP:

GET /api/services/example/testMethod
POST /api/services/example/calculate

Configuration Options

The plugin accepts the following configuration options:

OptionTypeDefaultDescription
servicesPathString'services'Path to the directory containing service classes
baseRouteString'/api/services'Base route for all service endpoints
responseFormatString'json'Response format (currently only 'json' is supported)
autoloadBooleantrueWhether to auto-load services on startup
errorHandlerFunctionnullCustom error handler function

Response Format

Successful responses have the following format:

{
  "success": true,
  "data": {
    // The data returned by your service method
  },
  "meta": {
    "service": "Example",
    "method": "testMethod",
    "timestamp": "2025-02-28T09:30:00.000Z"
  }
}

Error responses have the following format:

{
  "success": false,
  "error": {
    "message": "Error message",
    "type": "Error",
    "status": 500
  },
  "meta": {
    "service": "Example",
    "method": "testMethod",
    "timestamp": "2025-02-28T09:30:00.000Z"
  }
}

Plugin System Integration

The RouterClassMethod plugin integrates with the Flow Server Framework plugin system following the "pif paf hopla" philosophy:

Auto-discovery (Pif)

The plugin automatically discovers service classes in the configured servicesPath directory. It recursively scans the directory and loads all JavaScript files that export a class.

// Example of how the plugin discovers services
const fs = require('fs');
const path = require('path');

function discoverServices(servicesPath) {
  const services = new Map();
  const files = fs.readdirSync(servicesPath);
  
  for (const file of files) {
    if (file.endsWith('.js')) {
      const ServiceClass = require(path.join(servicesPath, file));
      const serviceName = file.replace('.js', '');
      services.set(serviceName.toLowerCase(), ServiceClass);
    }
  }
  
  return services;
}

Auto-configuration (Paf)

The plugin automatically configures routes for each service method, making them accessible via HTTP endpoints. It uses the service name and method name to create the route path.

// Example of how the plugin configures routes
function configureRoutes(httpEngine, services, baseRoute) {
  for (const [serviceName, ServiceClass] of services.entries()) {
    const methods = Object.getOwnPropertyNames(ServiceClass)
      .filter(name => typeof ServiceClass[name] === 'function' && name !== 'constructor');
    
    for (const methodName of methods) {
      const routePath = `${baseRoute}/${serviceName}/${methodName}`;
      httpEngine.post(routePath, async (ctx) => {
        // Route handler implementation
      });
    }
  }
}

Auto-adaptation (Hopla)

The plugin adapts to different environments and configurations, allowing for customization of:

  • Service discovery paths
  • Base route
  • Response format
  • Error handling
  • Method naming conventions

Plugin Structure

flow-server-plugin-routerClassMethod/
├── src/
│   ├── index.js           # Main plugin code
│   ├── ServiceLoader.js   # Service discovery and loading
│   └── RouteHandler.js    # HTTP route handling
├── example/
│   ├── app.js             # Example usage
│   └── services/          # Example service classes
├── package.json
└── README.md

Integration with Other Plugins

The RouterClassMethod plugin can work alongside other Flow Server Framework plugins. For example:

  • Authentication plugins can provide middleware for securing service endpoints
  • Logging plugins can track service method calls
  • Cache plugins can cache service method responses

License

MIT

1.0.0

4 months ago