Thursday 18 January 2018

My friend's new npm module: express-controller-routing

Hello. My friend doesn't use reddit yet and I thought I would shamelessly promote his npm module express-controller-routing. I have been using it for about a year. It would be great if you guys would have a look at it.Basically it allows you to write express routers in a very succinct way that is easier to read, and easier to test. Here is some example code where i define a router (taken from a real project), and how it is required in app.js.// app.js const controller = require('express-controller-routing'); const clubhouseRoutes = require('./routes/clubhouse.routes')(knex); // knex is my database dependecy for my router const clubhouseController = controller(clubhouseRoutes); app.use('/clubhouses', clubhouseController); // clubhouse.routes.js 'use strict'; const assert = require('assert'); module.exports = function clubhouseRoutes(knex) { assert(knex, 'Knex must be provided'); return { '/': { get: function getAllClubhouses(req, res, next) { return knex.select().from('clubhouses').limit(20) .then(clubhouses => res.json(clubhouses)) .catch(next); }, post: [someMiddleware, function(req, res, next) { //@todo }], }, ' /:id/image': { get: function getClubhouseImages(req, res, next) { req.checkParams('id', 'Clubhouse id must be integer').isInt(); const errors = req.validationErrors(); if (errors) { return next(errors); } const { id } = req.params; return knex.select('image').from('clubhouse_images').where('id', id) .then(images => res.json(images)) .catch(next); } } }; } This is great for unit testing and partial integration tests, because your route definitions are no longer coupled to express. Also this is just a very simple way of organising your routes. Let me know what you think! And try it out!

Submitted January 18, 2018 at 03:43PM by davidmdm

No comments:

Post a Comment