Created
August 21, 2015 14:29
-
-
Save shalotelli/c12e95c970811ffcdc5c to your computer and use it in GitHub Desktop.
Node automatic rest routes
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 _ = require('lodash'); | |
function Crud(Model) { | |
this.Model = Model; | |
} | |
Crud.prototype.find = function(req, res) { | |
var criteria = {}, | |
findMethod = 'find'; | |
if (req.params.id) { | |
criteria._id = req.params.id; | |
findMethod = 'findOne'; | |
} | |
if (!_.isEmpty(req.query)) { | |
criteria = _.extend(criteria, req.query); | |
} | |
return this.Model[findMethod](criteria, function(err, documents) { | |
if (err) { | |
return res.status(501).json(err); | |
} | |
return res.json(documents); | |
}); | |
}; | |
Crud.prototype.create = function(req, res) { | |
var document; | |
if (req.body) { | |
document = new this.Model(req.body); | |
document.save(function(err) { | |
if (err) { | |
return res.status(501).json(err); | |
} | |
return res.json(document); | |
}); | |
} else { | |
return res.status(400).json({ | |
success: false | |
}); | |
} | |
}; | |
Crud.prototype.update = function(req, res) { | |
if (req.params.id) { | |
this.Model.findOne({ | |
_id: req.params.id | |
}, function(err, document) { | |
if (err) { | |
return res.status(501).json(err); | |
} | |
document = _.extend(document, req.body); | |
document.save(function(err) { | |
if (err) { | |
return res.status(501).json(err); | |
} | |
return res.json(document); | |
}); | |
}); | |
} | |
}; | |
Crud.prototype.delete = function(req, res) { | |
if (req.params.id) { | |
this.Model.findOneAndRemove({ | |
_id: req.params.id | |
}, function(err, document) { | |
if (err) { | |
return res.status(501).json(err); | |
} | |
return res.json(document); | |
}); | |
} else { | |
return res.status(400).json({ | |
success: false | |
}); | |
} | |
}; | |
module.exports = Crud; |
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, controller) { | |
var path = '/' + route, | |
pathWithId = path + '/:id'; | |
app.get(path, function(req, res) { | |
controller.find(req, res); | |
}); | |
app.get(pathWithId, function(req, res) { | |
controller.find(req, res); | |
}); | |
app.post(path, function(req, res) { | |
controller.create(req, res); | |
}); | |
app.put(pathWithId, function(req, res) { | |
controller.update(req, res); | |
}); | |
app.delete(pathWithId, function(req, res) { | |
controller.delete(req, res); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment