import express from 'express';
import { logger } from '../services';

const router = new express.Router();
export default router;

const routes = [
  'home',
  'login',
  'login/callback',
  'token',
  'report/svg', // report/svg must place before repo/report.
  'repo/report',
];

routes.forEach(name => {
  const module = require(`./${name}`);
  const route = router.route(module.route);

  logger.debug(`[routes] route [${module.route}] from file [${name}] provides functions [${Object.keys(module)}].`);
  route.all((req, res, next) => {
    logger.debug(`[routes] request [${req.method}] path [${req.url}], hit route [${module.route}] from file [${name}].`);
    next();
  });

  if (module.post) {
    const middlewares = module.post.middlewares || [];
    route.post(
      ...middlewares,
      (req, res) =>
        module.post(req).then(result =>
          // TODO negotiate with req Accept filed to response result
          req.xhr ? res.send(result) : res.redirect(req.get('Referer'))));
  }

  if (module.redirect) {
    route.get((req, res) =>
      module.redirect(req).then(url => res.redirect(url)));
  } else if (module.view && module.model) {
    route.get((req, res) =>
      module.model(req).then(model =>
        res.type(module.type || 'html').render(module.view, model)));
  } else {
    route.get((req, res) =>
      res.status(500).end());
  }
});

@@ -124,16 +124,193 @@
 outer;%0A%0A
+function handleError(res) %7B%0A  return (error) =%3E %7B%0A    // TODO implement more safe error handling%0A    logger.warn(error);%0A    res.status(error.code).send(error.message);%0A  %7D;%0A%7D%0A%0A
 const ro
@@ -1007,24 +1007,35 @@
 le.post(req)
+%0A          
 .then(result
@@ -1048,24 +1048,26 @@
         
+  
 // TODO 
 negotiat
@@ -1062,129 +1062,214 @@
 ODO 
-negotiate with req Accept filed to response result%0A          req.xhr ? res.send(result) : res.redirect(req.get('Referer')
+leverage %60res.format%60 to better content-negotiation%0A            req.accepts('html') === 'html'%0A            ? res.redirect(req.get('Referer'))%0A            : res.send(result))%0A          .catch(handleError(res
 )));
@@ -1349,24 +1349,33 @@
 edirect(req)
+%0A        
 .then(url =%3E
@@ -1392,16 +1392,49 @@
 ect(url)
+%0A        .catch(handleError(res))
 ));%0A  %7D 
@@ -1524,16 +1524,25 @@
 del(req)
+%0A        
 .then(mo
@@ -1552,24 +1552,26 @@
  =%3E%0A        
+  
 res.type(mod
@@ -1617,16 +1617,49 @@
  model))
+%0A        .catch(handleError(res))
 );%0A  %7D e

Add simple content-negotiate and error handling.