Skip to content

Instantly share code, notes, and snippets.

@eloytoro
Created June 13, 2015 18:55
Show Gist options
  • Save eloytoro/643c75c066d127a56975 to your computer and use it in GitHub Desktop.
Save eloytoro/643c75c066d127a56975 to your computer and use it in GitHub Desktop.
var router = require(/* definir un nombre unico */ 'koa-router'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Report = mongoose.model('Report'),
// home seria el router que parte desde el url '/'
home = router(),
users = home.route('/users'),
reports = home.route(
// no se si sea buena idea incluir el '/' al comienzo del regex
/\/(reports|users\/:user\/reports)/
),
report = reports.route('/')
user = users.route('/:user');
users.get('/', function* (next) {
this.response.body = yield User.find();
});
user.get('/', function* (next) {
this.response.body = this.user;
});
user.put('/', function* (next) {
this.user.eachPath((path) => {
var val = this.request.body[path]
this.user.set(path, val);
});
});
home.param('user', function* (next, value) {
this.user = yield User.findById(value);
if (!this.user) yield new Error('UserNotFound');
yield next;
if (this.user.isModified()) {
yield this.user.save();
}
});
reports.param('report', function* (next, value) {
this.report = yield Report.findById(value);
if (!this.report) yield new Error('ReportNotFound');
yield next;
if (this.report.isModified()) {
yield this.report.save();
}
});
module.exports = home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment