Skip to content

New express router #2

@mateusnroll

Description

@mateusnroll

The current routing capabilities the default express router has are not enough for robust web applications. Although it's powerful, it's too verbose at times.

Each route needs you to require and instantiate the controller, and then apply a class method to a route. That method needs to accept req and res, and then everything works. Like this:

// Require everything
const express = require('express');
const r       = express.Router();

// Samples
let SamplesController = new (require('controllers/samples.controller.js'))();
r.get   ('/samples',      SamplesController.index   );
r.post  ('/samples',      SamplesController.create  );
r.get   ('/samples/new',  SamplesController.show    );
r.get   ('/samples/edit', SamplesController.edit    );
r.put   ('/samples',      SamplesController.update  );
r.delete('/samples',      SamplesController.destroy );

Rails' router does a great job at this, a couple lines can get a lot done. Getting inspiration from there, this is what we should have on ike. Node ActionRouter by Jared Hanson is a great inspiration on how to get it done.

Match routes without requiring the controllers

Avoid importing files, since we know where they are. Let the user describe them as easily as possible.

routes.match('samples/:id', { controller: 'samples', action: 'show' });

Or, even simpler, use a string format to get to it:

routes.match('samples/:id', 'samples#show');

Middlewares can be declared inline, without interrupting the readability:

routes.match('samples/:id', { controller: 'samples', action: 'show', middleware: [middleware, anotherMiddleware] });
// Or the short way
routes.match('samples/:d', 'samples#show', [middleware, anotherMiddleware]);

Resource mapping

Common resources share the basic functionality. Having to declare all properties might be cumbersome, and a helper can get that job done.

routes.resources('samples');

This would map to:

Method Path Action
GET /samples index
GET /samples/new new
POST /samples create
GET /samples/:id show
GET /samples/:id/edit edit
PUT /samples/:id update
DELETE /samples/:id destroy

Helpers for links

Providing helpers to deal with linking is the ideal way, since it keeps the views or controllers from hardcoding it. Changing the route on the routes file is enough to update it everywhere.

samplesPath('1b23ef'); // Would return /samples/1b23ed

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions