I would like to gather ideas on how to refactor the JavaScript/NodeJS controller code below to be more aesthetic. The code is using the koa framework thus I use yield
commands. I also use mongoose (I'm waiting for 3.9.2 which will support promises).
As a Ruby on Rails developer, I'm searching for a Rails-style way on writing NodeJS programs.
'use strict'
/*
* Model dependencies
*/
var _ = require('lodash')
var parse = require('co-body')
var db = require('mongoose-glue')
/*
* User controller.
*/
module.exports = {
/*
* Lists available users.
*/
index: function*(id) {
var skip, limit
skip = Math.max(0, this.query.skip)
limit = Math.min(10, this.query.limit)
this.body = yield db.model('user').find().skip(skip).limit(limit).exec()
},
/*
* Displays user with an id.
*/
show: function*(id) {
this.body = yield db.model('user').findById(id).exec()
this.status = this.body ? 200 : 404
},
/*
* Creates a new user.
*/
create: function*() {
var data
try {
data = yield formData(this, 'name')
this.body = yield createUser(data)
this.status = 201
} catch(e) {
this.body = e
this.status = 403
}
},
/*
* Updates user with an id.
*/
update: function*(id) {
var data
try {
data = yield formData(this, 'name')
this.body = yield updateUser(id, data)
} catch(e) {
this.body = e
this.status = 403
}
},
/*
* Removes user with an id.
*/
destroy: function*(id) {
var item
try {
item = yield destroyUser(id)
this.status = item ? 200 : 404
} catch(e) {
this.body = e
this.status = 403
}
},
}
/*
* Create user thunk
*/
function createUser(data) {
return function(next) {
db.model('user').create(data, next)
}
}
/*
* Update user thunk.
*/
function updateUser(id, data) {
return function(next) {
db.model('user').findByIdAndUpdate(id, data, next)
}
}
/*
* Create user thunk
*/
function destroyUser(id) {
return function(next) {
db.model('user').findByIdAndRemove(id, next)
}
}
/*
* Returns form data.
*/
function *formData(ctx) {
var data
data = yield parse.form(ctx)
data = _.any(arguments) ? _.pick(data, arguments) : data
return data
}