Adam Terlson
Adam Terlson

Reputation: 12730

Express router param - chaining with URL

I have a full CRUD API defined in Express, and I'd like to remove the duplication of base and use the snazzy route function, but I fear it's not possible.

Current:

var router = express.Router();
var base = '/api/foo/bar/';
router.get(base, this.list);
router.get(base + ':id', this.read);
router.post(base, this.create);
router.put(base + :id', this.update);
router.del(base + :id', this.del);

Desired:

var router = express.Router();
router.route('/api/foo/bar')
  .get(this.list)
  .get(':id', this.read)
  .post(this.create)
  .put(':id', this.update)
  .del(':id', this.del)

The problem is that the verb functions (get, post, put, del) do not accept a string as their first parameter.

Is there a similar way to achieve this?

Upvotes: 2

Views: 5026

Answers (1)

mscdex
mscdex

Reputation: 106696

Important: Using this technique will work, but we aware that as of Express 4.3.2, all subroutes defined on the nested router will not have access to req.params defined outside of it, nor param middleware. It's completely quarantined. This, however, is subject to change in a later 4X version. See https://github.com/visionmedia/express/issues/2151 for more (up to date) info.


How about this instead:

// api.js
var router = express.Router();
router
  .route('/')
    .get(this.list)
    .post(this.create);
router
  .route('/:id')
    .get(this.read)
    .put(this.update)
    .del(this.del);
module.exports = router;

// app.js / main.js
app.use('/api/foo/bar', require('./api'));

or if you want to chain all of them at once:

// api.js
var router = express.Router();
router
  .get('/', this.list)
  .get('/:id', this.read)
  .post('/', this.create)
  .put('/:id', this.update)
  .del('/:id', this.del);
module.exports = router;

// app.js / main.js
app.use('/api/foo/bar', require('./api'));

Upvotes: 9

Related Questions