app-routes

0.1.0 • Public • Published

app-routes

Route mapping kinda like Rails

install

npm install app-routes

config/routes.js file

var appRoutes   = require('app-routes')(__dirname),
    match       = appRoutes.match,
    resources   = appRoutes.resources,
    root        = appRoutes.root;
 
var routes = {
    draw: function (app) {
        root(app, 'home#index');
 
        // alias
        match(app, 'get', 'signup', 'users#create');
 
        // standard REST actions
        resources(app, 'users');
    }
};
 
module.exports = routes;

web.js (app.js, server.js)

var express         = require('express'),
    app             = express(),
    routes          = require('./config/routes');
...
routes.draw(app);

controller

var _   = require('underscore'),
    Foo = require('../models/foo');
 
var fooController = {
 
    // add middleware
    beforeActions: [
        { filter: authorize },
        { filter: findFoo, only: ['update'] }
    ],
 
    index: function (req, res, next) {
        res.json([]);
    },
 
    update: function (req, res, next) {
        var foo = fooParams(req);
 
        Foo.findByIdAndUpdate(req.params.id, foo, function (err, doc) {
            if (err) return next(err);
 
            res.json(doc);
        });
    }
};
 
function authorize (req, res, next) {
    // find user by some token/cookie/header
    if (!cool) {
        return next(new Error('not cool'));
    }
 
    next();
};
 
function findFoo () {
    Foo.findById(req.params.id, function (err, doc) {
        if (err) return next(err);
 
        req.foo = doc;
        next();
    });
};
 
// whitelist values from client (like Rails 4)
function fooParams (req) {
    return _.pick(req.body, 'bar', 'baz');
};
 
module.exports = fooController;

Readme

Keywords

none

Package Sidebar

Install

npm i app-routes

Weekly Downloads

2

Version

0.1.0

License

MIT

Last publish

Collaborators

  • rschooley