// app.js
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
// routes.js It's just a mapping.
exports.routes = [
['/', controllers.index],
['/posts', controllers.posts.index],
['/posts/:post', controllers.posts.show]
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request
The final app.js:
// app.js
var express = require('express');
var app = express.createServer();
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
Another version: you can customize this according to your own needs, like adding post request
// routes.js It's just a mapping.
let get = ({path, callback}) => ({app})=>{
app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
// ...custom logic
app.get(path, callback);
}
exports.routes = [
get({path: '/', callback: controllers.index}),
post({path: '/posts', callback: controllers.posts.index}),
someFn({path: '/posts/:post', callback: controllers.posts.show}),
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => route({app}));