UNPKG

yahoi

Version:

Yet Another Highly Opinionated Isomorphic Framework

153 lines (98 loc) 2.85 kB
const RouteParser = require('route-parser'); const path = require('path'); export default class Route { constructor(options) { if(typeof(options.app)=='undefined' || options.app==null) { throw Error('FATAL: No app reference defined for Route: ' + options.path); } this.app = options.app; if(typeof(options.type)=='undefined') { this.__type = 'get'; } else { this.__type = options.type.toLowerCase(); } this.__router = null; if(typeof(options.path)==='function') { this.path = options.path; this.__routeParser = null; } else { this.path = options.path; this.__routeParser = new RouteParser(options.path); } if(typeof(options.router)!='undefined') { this.__router = null; } else { this.__controllerName = options.controller; this.__actionName = options.action; this.__controller = this.loadController(options.controller); } this.loadController = this.loadController.bind(this); } getType() { return this.__type; } setAppReference(app) { this.app = app; } getRouter() { return this.__router; } loadRouter(routerName) { var router = this.app.createRouter(routerName, { app: this.app }); router.setPrefix(this.path); return router; } loadController(controller) { return this.app.getController(controller); } getController() { return this.__controller; } getActionName() { return this.__actionName; } getControllerName() { return this.__controllerName; } renderAction(req, res, match) { return this.getController().renderAction(this.getActionName(), req, res, match); } getPath() { return this.path; } buildPathToMatch(path, prefix = '') { prefix = prefix.replace('*wild', "") if(prefix.length>0) { path = prefix + path; } else { path = path; } path = path.replace(/([^:]\/)\/+/g, "$1"); return path; } match(req, options = {}) { let prefix = options.prefix || null; let requestUrl = req.url; let path = this.path; let routeParser = this.__routeParser; if(typeof(this.path)==='function') { path = this.path(req); routeParser = new RouteParser(path); } //console.log(`compare: ${req.type} == ${this.getType()}`, ) if(req.method.toLowerCase()!=this.getType()) { return null; } let match = routeParser.match(requestUrl); let isMatchX = match ? "X" : ""; //console.log(`matching ${req.url} against ${path} => ${isMatchX}`) if(match) { return { route: this, match: match }; } else { return null; } } }