UNPKG

fortify2-js

Version:

MOST POWERFUL JavaScript Security Library! Military-grade cryptography + 19 enhanced object methods + quantum-resistant algorithms + perfect TypeScript support. More powerful than Lodash with built-in security.

273 lines (269 loc) 10.4 kB
'use strict'; var Logger = require('../../utils/Logger.js'); /** * RouteManager - Handles all route-related operations for FastApi.ts * Manages HTTP methods with caching, route templates, and optimization */ class RouteManager { constructor(dependencies) { this.dependencies = dependencies; } /** * Add all HTTP methods with caching support to the Express app */ addMethods() { Logger.logger.debug("routes", "Adding HTTP methods with caching support..."); this.addGetWithCache(); this.addPostWithCache(); this.addPutWithCache(); this.addDeleteWithCache(); this.addCacheManagementMethods(); this.addPerformanceOptimizationMethods(); this.addUltraFastOptimizerMethods(); // logger.debug( "routes","HTTP methods added successfully"); } /** * Add GET method with caching support */ addGetWithCache() { this.dependencies.app.getWithCache = (path, routeOptions, handler) => { const cacheMiddleware = this.dependencies.middlewareManager.createCacheMiddleware({ ttl: routeOptions.cache?.ttl, keyGenerator: (req) => this.dependencies.cacheManager.generateCacheKey(req), }); this.dependencies.app.get(path, cacheMiddleware, handler); }; } /** * Add POST method with cache invalidation */ addPostWithCache() { this.dependencies.app.postWithCache = (path, routeOptions, handler) => { const wrappedHandler = async (req, res, next) => { try { await handler(req, res, next); // Invalidate cache if specified if (routeOptions.cache?.invalidateOn) { await this.dependencies.cacheManager .getCache() .invalidateByTags(routeOptions.cache.invalidateOn); } } catch (error) { next(error); } }; this.dependencies.app.post(path, wrappedHandler); }; } /** * Add PUT method with cache invalidation */ addPutWithCache() { this.dependencies.app.putWithCache = (path, routeOptions, handler) => { const wrappedHandler = async (req, res, next) => { try { await handler(req, res, next); // Invalidate cache if specified if (routeOptions.cache?.invalidateOn) { await this.dependencies.cacheManager .getCache() .invalidateByTags(routeOptions.cache.invalidateOn); } } catch (error) { next(error); } }; this.dependencies.app.put(path, wrappedHandler); }; } /** * Add DELETE method with cache invalidation */ addDeleteWithCache() { this.dependencies.app.deleteWithCache = (path, routeOptions, handler) => { const wrappedHandler = async (req, res, next) => { try { await handler(req, res, next); // Invalidate cache if specified if (routeOptions.cache?.invalidateOn) { await this.dependencies.cacheManager .getCache() .invalidateByTags(routeOptions.cache.invalidateOn); } } catch (error) { next(error); } }; this.dependencies.app.delete(path, wrappedHandler); }; } /** * Add cache management methods to the app */ addCacheManagementMethods() { // Cache invalidation method this.dependencies.app.invalidateCache = async (pattern) => { await this.dependencies.cacheManager.invalidateCache(pattern); }; // Cache statistics method this.dependencies.app.getCacheStats = async () => { return await this.dependencies.cacheManager.getCacheStats(); }; // Cache warm-up method this.dependencies.app.warmUpCache = async (data) => { await this.dependencies.cacheManager.warmUpCache(data); }; } /** * Add performance optimization methods to the app */ addPerformanceOptimizationMethods() { // Performance optimization methods will be added by PerformanceManager // This is a placeholder for future expansion } /** * Add UltraFastOptimizer methods to the app */ addUltraFastOptimizerMethods() { // Route template registration this.dependencies.app.registerRouteTemplate = (template) => { this.dependencies.ultraFastOptimizer?.registerRoute(template); }; // Route template unregistration this.dependencies.app.unregisterRouteTemplate = (route, method) => { if (this.dependencies.ultraFastOptimizer) { const pattern = route instanceof RegExp ? route : route; this.dependencies.ultraFastOptimizer.unregisterRoute(pattern); } }; // Optimization pattern registration this.dependencies.app.registerOptimizationPattern = (pattern) => { this.dependencies.ultraFastOptimizer?.registerRoute(pattern); }; // Optimizer statistics this.dependencies.app.getOptimizerStats = () => { return this.dependencies.ultraFastOptimizer?.getStats() || null; }; } /** * Setup default optimized routes for common endpoints */ setupDefaultOptimizedRoutes() { if (!this.dependencies.ultraFastOptimizer) return; Logger.logger.debug("routes", "Setting up default optimized routes..."); // Import QuickRoutes for default route templates try { const { QuickRoutes, } = require("../../optimization/UltraFastOptimizer"); // Register common health/status routes this.dependencies.ultraFastOptimizer.registerRoute(QuickRoutes.healthCheck); this.dependencies.ultraFastOptimizer.registerRoute(QuickRoutes.apiStatus); Logger.logger.debug("routes", "Default optimized routes configured"); } catch (error) { console.warn("Failed to setup default optimized routes:", error.message); } } /** * Register custom route templates from configuration */ registerCustomRouteTemplates(routeTemplates) { if (!this.dependencies.ultraFastOptimizer || !routeTemplates) return; Logger.logger.debug("routes", "Registering custom route templates..."); try { // Convert RouteTemplate to OptimizedRoute format for (const template of routeTemplates) { const optimizedRoute = { pattern: template.route, methods: template.method ? [template.method] : undefined, handler: template.generator, schema: template.schema, cacheTTL: template.cacheTTL, priority: template.priority, }; this.dependencies.ultraFastOptimizer.registerRoute(optimizedRoute); } Logger.logger.debug("routes", `Registered ${routeTemplates.length} custom route templates`); } catch (error) { console.warn("Failed to register custom route templates:", error.message); } } /** * Get route statistics and information */ getRouteStats() { return { totalRoutes: this.dependencies.app._router?.stack?.length || 0, summary: this.dependencies.ultraFastOptimizer?.getStats(), cacheEnabled: true, timestamp: new Date().toISOString(), }; } /** * Validate route configuration */ validateRouteConfig(path, options) { try { // Basic path validation if (!path || typeof path !== "string") { console.warn(`Invalid route path: ${path}`); return false; } // Cache configuration validation if (options.cache) { if (options.cache.ttl && (typeof options.cache.ttl !== "number" || options.cache.ttl < 0)) { console.warn(`Invalid cache TTL for route ${path}: ${options.cache.ttl}`); return false; } if (options.cache.tags && !Array.isArray(options.cache.tags)) { console.warn(`Invalid cache tags for route ${path}: must be an array`); return false; } } // Security configuration validation if (options.security) { if (options.security.roles && !Array.isArray(options.security.roles)) { console.warn(`Invalid security roles for route ${path}: must be an array`); return false; } } return true; } catch (error) { console.warn(`Route validation failed for ${path}:`, error.message); return false; } } /** * Get route middleware chain information */ getRouteMiddleware(path) { try { const router = this.dependencies.app._router; if (!router || !router.stack) return []; const middlewareStack = router.stack .filter((layer) => layer.route?.path === path) .map((layer) => ({ name: layer.name || "anonymous", path: layer.route?.path, methods: layer.route?.methods, })); return middlewareStack; } catch (error) { console.warn(`Failed to get middleware for route ${path}:`, error.message); return []; } } } exports.RouteManager = RouteManager; //# sourceMappingURL=RouteManager.js.map