UNPKG

light-ning

Version:

(ALPHA) framework without dependecies...

84 lines (65 loc) 2.37 kB
import { Response } from './app'; import { capitalize, isArray } from './lib'; import middlewares from './middlewares'; import app from './app'; class Router { routers = []; rootPaths = []; controllersPath; guardian; setControllersPath(path) { this.controllersPath = path; } setGuardian(guardian) { this.guardian = guardian; } routes(rootPath, routes) { if (isArray(routes)) { this.rootPaths.push(rootPath); this.routers.push(routes); } else { throw new Error('routes in "Router" must be array.'); } } route(req, res) { const {url, method} = req; this.routers.map((router, routerIndex) => { router.map(route => { route.method = route.method.toUpperCase(); const response = new Response(res); let rootPath = this.rootPaths[routerIndex]; const run = () => { if (route.middleWares && !route.action) { return middlewares(req, res, route.middleWares); } else if (route.middleWares && route.action) { throw new Error('params: action and middleWares cannot work together'); } const urlCondition = ((url === '/' ? '' : url) + '/'); if (rootPath === '/' && route.path === '/') rootPath = ''; if ((urlCondition === `${rootPath}${route.path}` || url === `${rootPath}${route.path}`) && method === route.method) { let [name, action] = route.action.split('@'); let Controller, controllerName = capitalize(name); try { Controller = new (require(`${this.controllersPath}/${name}`)[controllerName]); } catch(e) { throw new Error(`${controllerName} controller contains error or cannot find "${this.controllersPath}/${name}" in ${app.get('base')}`); } this.action(req, res, Controller[action].bind(Controller), response); } }; if (route.guard) { if (this.guardian) { return this.guardian({ req: req, res: res, next: run, response: response }); } else { throw new Error('"guardian" is undefined. Please, set guardian in app.'); } } run(); }) }); } action(req, res, method, response) { method({ req: req, res: res, response: response }); } } export default new Router();