Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Forked from clarkf/route.js
Created February 10, 2012 06:11
Show Gist options
  • Save chrisdickinson/1787118 to your computer and use it in GitHub Desktop.
Save chrisdickinson/1787118 to your computer and use it in GitHub Desktop.
DRY?
exports.whater = function (req, res) {
var format = req.params.format ? req.params.format : req.format;
User.findOne({ username: req.params.username }, function (err, doc) {
if (err) throw err;
if (!doc) {
if (format == 'json') {
res.json({ error: "no such user"});
} else {
res.render('404');
}
} else {
if (format == 'json') {
res.json(doc);
} else {
res.render('user/show', { user: doc });
}
}
});
};
// or split it out
exports.whater = function(req, res) {
var fmt = req.params.format || req.format
, respond = (format === 'json' ? respond_json : respond_html).bind(this, req, res)
User.findOne({username:req.params.username}, respond)
}
function respond_json(req, res, err, user) {
res.json(err ?
{error:'no such user'} :
user
)
}
function respond_html(req, res, err, user) {
res.render.apply(res, err ?
['404']
: ['user/show', {user:user}]
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment