add example controller and lib to setup routes

This commit is contained in:
Matteo Pagliazzi
2015-11-15 22:40:00 +01:00
parent 83eb2308fb
commit 448ed70ab9
3 changed files with 40 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
// An example file to show how a controller should be structured
let api = {};
api.exampleRoute = {
method: 'GET',
url: '/example/:param',
middlewares: [],
handler (req, res) {
res.status(200).send({
status: 'ok'
});
},
};
export default api;

View File

@@ -0,0 +1,23 @@
import fs from 'fs';
import path from 'path';
import express from 'express';
import _ from 'lodash';
const CONTROLLERS_PATH = path.join(__dirname, '/../../controllers/api-v3/');
let router = express.Router();
fs
.readdirSync(CONTROLLERS_PATH)
.filter(fileName => fileName.match(/\.js$/))
.filter(fileName => fs.statSync(CONTROLLERS_PATH + fileName).isFile())
.forEach((fileName) => {
let controller = require(CONTROLLERS_PATH + fileName);
_.each(controller, (action) => {
let {method, url, middlewares, handler} = action;
method = method.toLowerCase();
router[method](url, ...middlewares, handler);
});
});
export default router;

View File

@@ -3,6 +3,7 @@
import analytics from './analytics'; import analytics from './analytics';
import errorHandler from './errorHandler'; import errorHandler from './errorHandler';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';
import routes from '../../libs/api-v3/setupRoutes';
export default function attachMiddlewares (app) { export default function attachMiddlewares (app) {
// Parse query parameters and json bodies // Parse query parameters and json bodies
@@ -14,6 +15,7 @@ export default function attachMiddlewares (app) {
app.use(analytics); app.use(analytics);
app.use(routes);
// Error handler middleware, define as the last one // Error handler middleware, define as the last one
app.use(errorHandler); app.use(errorHandler);
} }