All files / express/src coherent-express.js

23.68% Statements 9/38
55% Branches 11/20
33.33% Functions 3/9
23.68% Lines 9/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                                    3x   3x                                                                         1x                                                                                               1x     1x 1x 1x       1x 1x                                                                          
/**
 * Enhanced Express.js integration for Coherent.js
 * Provides middleware and utilities for using Coherent.js with Express
 */
 
import {
  render,
  importPeerDependency,
  renderWithTemplate,
  renderComponentFactory,
  isCoherentComponent
} from '@coherent.js/core';
 
/**
 * Coherent.js Express middleware
 * Automatically renders Coherent.js components and handles errors
 *
 * @param {Object} options - Configuration options
 * @param {boolean} options.enablePerformanceMonitoring - Enable performance monitoring
 * @param {string} options.template - HTML template with {{content}} placeholder
 * @returns {Function} Express middleware function
 */
export function coherentMiddleware(options = {}) {
  const {
    enablePerformanceMonitoring = false,
    template = '<!DOCTYPE html>\n{{content}}'
  } = options;
 
  return (req, res, next) => {
    // Store original send method
    const originalSend = res.send;
 
    // Override send method to handle Coherent.js objects
    res.send = function(data) {
      // If data is a Coherent.js object (plain object with a single key), render it
      if (isCoherentComponent(data)) {
        try {
          // Use shared rendering utility
          const finalHtml = renderWithTemplate(data, { enablePerformanceMonitoring, template });
 
          // Set content type and send HTML
          res.set('Content-Type', 'text/html');
          return originalSend.call(this, finalHtml);
        } catch (_error) {
          console.error('Coherent.js rendering _error:', _error);
          return next(_error);
        }
      }
 
      // For non-Coherent.js data, use original send method
      return originalSend.call(this, data);
    };
 
    next();
  };
}
 
/**
 * Create an Express route handler for Coherent.js components
 *
 * @param {Function} componentFactory - Function that returns a Coherent.js component
 * @param {Object} options - Handler options
 * @returns {Function} Express route handler
 */
export function createCoherentHandler(componentFactory, options = {}) {
  return async (req, res, next) => {
    try {
      // Use shared rendering utility
      const finalHtml = await renderComponentFactory(
        componentFactory,
        [req, res, next],
        options
      );
 
      // Send HTML response
      res.set('Content-Type', 'text/html');
      res.send(finalHtml);
    } catch (_error) {
      console.error('Coherent.js handler _error:', _error);
      next(_error);
    }
  };
}
 
/**
 * Enhanced Express engine for Coherent.js views
 *
 * @param {string} filePath - Path to view file (not used in Coherent.js)
 * @param {Object} options - View options containing Coherent.js component
 * @param {Function} callback - Callback function
 */
export function enhancedExpressEngine(filePath, options, callback) {
  try {
    // Render Coherent.js component from options
    const html = render(options);
    callback(null, html);
  } catch (_error) {
    callback(_error);
  }
}
 
/**
 * Setup Coherent.js with Express app
 *
 * @param {Object} app - Express app instance
 * @param {Object} options - Setup options
 */
export function setupCoherent(app, options = {}) {
  const {
    useMiddleware = true,
    useEngine = true,
    engineName = 'coherent',
    enablePerformanceMonitoring = false
  } = options;
 
  // Register enhanced engine
  Eif (useEngine) {
    app.engine(engineName, enhancedExpressEngine);
    app.set('view engine', engineName);
  }
 
  // Use middleware for automatic rendering
  Eif (useMiddleware) {
    app.use(coherentMiddleware({ enablePerformanceMonitoring }));
  }
}
 
/**
 * Create Express integration with dependency checking
 * This function ensures Express is available before setting up the integration
 *
 * @param {Object} options - Setup options
 * @returns {Promise<Function>} - Function to setup Express integration
 */
export async function createExpressIntegration(options = {}) {
  try {
    // Verify Express is available
    await importPeerDependency('express', 'Express.js');
 
    return function(app) {
      if (!app || typeof app.use !== 'function') {
        throw new Error('Invalid Express app instance provided');
      }
 
      setupCoherent(app, options);
      return app;
    };
  } catch (_error) {
    throw _error;
  }
}
 
// Export all utilities
export default {
  coherentMiddleware,
  createCoherentHandler,
  enhancedExpressEngine,
  setupCoherent,
  createExpressIntegration
};