UNPKG

yml-mvc-router

Version:

A configurable, Express-compatible routing module that maps routes from YAML to controllers following the MVC pattern

80 lines (68 loc) 2.01 kB
/** * Handles asset injection into res.locals */ class Assets { constructor(config) { this.config = config; } /** * Create middleware to inject assets into res.locals * @param {Object} assets - Assets configuration from route * @returns {Function} Express middleware */ createMiddleware(assets = {}) { return (req, res, next) => { // Initialize res.locals.assets if not exists if (!res.locals.assets) { res.locals.assets = { css: [], js: [] }; } // Add route-specific assets if (assets.css) { res.locals.assets.css.push(...this._resolveAssets(assets.css)); } if (assets.js) { res.locals.assets.js.push(...this._resolveAssets(assets.js)); } next(); }; } /** * Resolve asset paths * @param {Array|string} assetPaths - Asset path(s) * @returns {Array} Resolved asset URLs */ _resolveAssets(assetPaths) { const paths = Array.isArray(assetPaths) ? assetPaths : [assetPaths]; return paths.map(assetPath => { // If already absolute URL, return as-is if (assetPath.startsWith('http://') || assetPath.startsWith('https://') || assetPath.startsWith('//')) { return assetPath; } // If starts with /, treat as absolute path from web root if (assetPath.startsWith('/')) { return assetPath; } // Otherwise, prepend with assets base path return '/' + assetPath; }); } /** * Generate HTML tags for assets (utility for templates) * @param {Array} css - CSS file paths * @param {Array} js - JS file paths * @returns {Object} { cssTag, jsTag } HTML strings */ static generateTags(css = [], js = []) { const cssTag = css .map(href => `<link rel="stylesheet" href="${href}">`) .join('\n'); const jsTag = js .map(src => `<script src="${src}"></script>`) .join('\n'); return { cssTag, jsTag }; } } module.exports = Assets;