Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express Router Prefix

I am confused about how to properly set up API routing in my express app. What I would like to have is structured way to define routes without repeating myself. As a database I am using RethinkDB. For each model, let's say Exercise I have created a file in the models directory. These files only define the model / schema. I thought that each model also defines an endpoint for my API. Thus, I have created a routes folder in which I declare my routes in separate files, e.g. exercises.js. This is my directory structure:

root
├── app.js
├── bootstrap.js
├── routes
│   ├── exercises.js
│   ├── index.js
│   └── ...
├── models
│   ├── exercise.js
│   └── ...
└── ...

An example route file looks like this:

module.exports = (function() {
    'use strict';

    var router = express.Router();

    router.get('/exercises', getAllExercises);
    router.get('/exercises/:id', getExerciseById);

    return router;
})();

As you can see I am repeating the route prefix exercises. This is a sub-prefix because all routes should start with /api. Is it possible to define in a prefix for a single router, so that I use app.use('/api', [routers]) in the app.js and tell each router to have a different route prefix such as /api/excursions/? I am confused about my declaration and also ask for feedback. I think there is a better way to organize my API because with what I am doing right know I would also need to include all routes in the app.js to pass in all routes to the app as an array. This is my app.js:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var port = process.env.PORT || 3000;

app.use(bodyParser.json());

// API Routes
var exercises = require(__dirname + '/routes/exercises');

app.use('/api', [exercises]);

// Start the server
app.listen(port);
console.log('Listening on port '+ port);

The array syntax was taken from the offical express documentation.

like image 227
LordTribual Avatar asked Jun 21 '15 15:06

LordTribual


1 Answers

You can write your route files like so:

module.exports = function (app) {
    'use strict';

    var router = express.Router();

    router.get('/', getAllExercises);
    router.get('/:id', getExerciseById);

    app.use('/api/exercises', router);
};

And require each of them like this:

require('./routes/exercises')(app);

Note that you can replace __dirname + '/... with './....

like image 80
Patrick Roberts Avatar answered Oct 19 '22 14:10

Patrick Roberts