This repository has been archived on 2018-10-12. You can view files and clone it, but cannot push or open issues or pull requests.
ProgBlog/app/base/Controller.js

74 lines
1.9 KiB
JavaScript

'use strict';
const container = require('../Container');
const express = require('express');
const errors = require('errors');
const getArgs = require('getargs');
const loadRoutes = container.get('base/util/route-loader');
const _ = container.get('_');
/**
* Controller setup and utility class
*/
class Controller {
/**
* Get route mapping
*
* @param {string} baseRoutePath - the path to the folder containing
* controllers/routes
* @return {map} - Maps route prefixes to their respective functions
*/
static getRouteMap(baseRoutePath) {
const routeMap = {};
const pathFileMap = loadRoutes(baseRoutePath);
_(pathFileMap).forEach((routeFile, routePath) => {
let rawRoutes = require(routeFile);
routeMap[routePath] = Controller._parseRoutes(rawRoutes);
});
return routeMap;
}
/**
* Simplify route generation with an object
*
* @private
* @param {Object} routeObject - the object laying out the routes for the
* current controller
* @return {Router} - the updated express.Router object
*/
static _parseRoutes(routeObject) {
const router = express.Router();
_(routeObject).forEach((httpMethods, currentPath) => {
_(httpMethods).forEach((routeFunction, currentHttpMethod) => {
let routerMethod = router[currentHttpMethod];
return router[currentHttpMethod](currentPath, routeFunction);
});
});
return router;
}
/**
* Send a specific http error code
*
* @param {number} code - The error Number
* @param {Object} [options={}] - Options, such as message and explanation
* @param {function} next - The callback to pass the error to
* @return {void}
*/
static HttpError(/*code, options, next*/) {
let args = getArgs('code:Number, [options]:object, next:function', arguments);
args.options = args.options || {};
let methodName = `Http${args.code}Error`;
let err = new errors[methodName](args.options);
return args.next(err);
}
}
module.exports = Controller;