public
Created

One way to (sort of) rest (w Mongoose)

  • Download Gist
controller.js
JavaScript
1 2 3 4 5 6 7 8 9
var build = require('./crud.js').build
 
 
var gameController = build('Game')
// how to get this automatic? remember middleware
app.get( '/games', gameController.index)
app.get( '/games/:id', gameController.show)
app.post( '/games', gameController.save)
app.post( '/games/:id/delete', gameController.destroy)
crud.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
/*
* Rely on GLOBAL.app for a express server
* and GLOBAL.models for models defined (mongoose)
*/
 
function build(modelName, options){
function loadOne(id, cb) {
};
var controller = {
name: modelName,
index: function(req, res, next){
app.models[modelName].find({}, function(err, docs) {
res.json(
docs.map(function(e,i){ return e.toJSON() })
)
})
},
show: function(req, res, next){
// console.log( req.params.id )
app.models[modelName].findById( req.params.id , function(err, doc) {
if(err) res.json([0])
res.json( doc )
})
},
//edit: function(req, res, next){ },
save: function(req, res, next){
if( req.body && req.body[modelName.toLowerCase()] ){
saveCb = function(err, doc) {
// TODO
}
if( req.body[modelName.toLowerCase()]._id ){ //UPDATE
app.models[modelName].update({ _id: req.body[modelName.toLowerCase()]._id },
req.body[modelName.toLowerCase()],
saveCb
)
} else { // CREATE
(new app.models[modelName](req.body[modelName.toLowerCase()])).save( saveCb )
}
// FIXME
res.json( [1] )
} else {
res.json( [0] )
}
},
destroy: function(req, res, next){
if( req.params && req.params.id ){
res.json( [0] )
} else {
app.models[modelName].remove({ _id: req.params.id }, function(err, doc) {
res.json( doc.toJSON() )
})
}
},
}
return controller
}
 
exports.build = build

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.