Created
November 26, 2011 15:21
-
-
Save Raynos/1395845 to your computer and use it in GitHub Desktop.
Splitting up routers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Post = require("../domain/post.js"), | |
PostModel = require("../data/post.js"), | |
View = require("../view/post.js"); | |
var authorized = [ | |
function _requireLogin(req, res, next) { | |
if (req.user) { | |
next(); | |
} else { | |
res.redirect('/login/'); | |
} | |
}, | |
function _beRaynos(req, res, next) { | |
if (req.user.name === "Raynos") { | |
next(); | |
} else { | |
next(new Error("Your not Raynos")); | |
} | |
} | |
]; | |
function fetchPost(req, res, next) { | |
var id = parseInt(req.params.postId, 10); | |
Post.get(id, function _get(err, post) { | |
req.post = post; | |
next(); | |
}); | |
} | |
function validatePost(req, res, next) { | |
var errors = Post.validate(req.body); | |
if (errors) { | |
req.body.errors = errors; | |
return res.render("post/edit", View.view(req.body)); | |
} | |
next(); | |
} | |
module.exports = { | |
index: function _index(req, res) { | |
Post.all(function _all(err, posts) { | |
res.render("post/index", View.index(posts)); | |
}); | |
}, | |
new: [ | |
authorized, | |
function _new(req, res) { | |
res.render("post/new"); | |
} | |
], | |
edit: [ | |
fetchPost, | |
function _edit(req, res) { | |
res.render("post/edit", View.view(req.post)); | |
} | |
], | |
view: [ | |
fetchPost, | |
function _view(req, res) { | |
res.render("post/view", View.view(req.post)); | |
} | |
], | |
create: [ | |
authorized, | |
validatePost, | |
function _create(req, res) { | |
Post.create(req.body, function(err, post) { | |
res.redirect("/blog/" + View.makeUrl(post)); | |
}); | |
} | |
], | |
update: [ | |
authorized, | |
validatePost, | |
function _update(req, res) { | |
var id = parseInt(req.params.postId, 10); | |
Post.update(id, req.body, function(err, post) { | |
res.redirect("/blog/" + View.makeUrl(post)); | |
}); | |
} | |
] | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function _route(app, controller) { | |
app.get("/blog", controller.index); | |
app.get("/blog/new", controller.new); | |
app.get("/blog/:postId/edit", controller.edit); | |
app.get("/blog/:postId/:title?", controller.view); | |
app.post("/blog", controller.create); | |
app.put("/blog/:postId", controller.update); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment