yahoi
Version:
Yet Another Highly Opinionated Isomorphic Framework
101 lines (61 loc) • 1.88 kB
JavaScript
import Route from './Route';
const path = require('path');
export default class Router {
constructor(options = {}) {
if(typeof(options.app)=='undefined' || options.app==null) {
throw Error('FATAL: No app reference defined for Router with prefix: ' + options.prefix);
}
this.app = options.app;
this.routes = [];
this.prefix = options.prefix || null;
this.setAppReference = this.setAppReference.bind(this);
}
setPrefix(prefix) {
this.prefix = prefix;
}
getPrefix() {
return this.prefix;
}
getRoutes() {
return this.routes;
}
setAppReference(app) {
this.app = app;
}
addRoute(routeOptions) {
routeOptions.app = this.app;
var routerPath = routeOptions.path;
if(this.prefix) {
routerPath = this.prefix + routerPath;
}
if(typeof(routeOptions.router)!=='undefined') {
routeOptions.prefix = routerPath;
var _router = this.loadRouter(routeOptions.router, routeOptions);
this.routes.push(_router);
} else {
routeOptions.path = routerPath;
if(typeof(this.app)=='undefined' || this.app==null) {
throw Error(`Attempting to create a new route without an app reference: ${routerPath}`);
}
var route = new Route(routeOptions);
this.routes.push(route);
}
}
loadRouter(routerName, options) {
var router = this.app.createRouter(routerName, options);
router.setPrefix(this.path);
return router;
}
match(req, options = {}) {
for(var i = 0; i<this.routes.length; i++) {
let route = this.routes[i];
let matchResult = route.match(req);
if(matchResult) {
return {
route: matchResult.route,
match: matchResult.match
};
}
}
}
}