mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-01-07 14:12:43 +00:00
Cleaned up the server file and added methodfs and statics to the model
This commit is contained in:
@@ -53,17 +53,19 @@ router.post('/api', (req, res)=>{
|
||||
});
|
||||
|
||||
router.put('/api/update/:id', (req, res)=>{
|
||||
HomebrewModel.find({editId : req.params.id}, (err, objs)=>{
|
||||
if(!objs.length || err) return res.status(404).send("Can not find homebrew with that id");
|
||||
var resEntry = objs[0];
|
||||
resEntry.text = req.body.text;
|
||||
resEntry.title = req.body.title;
|
||||
resEntry.updatedAt = new Date();
|
||||
resEntry.save((err, obj)=>{
|
||||
if(err) return res.status(500).send("Error while saving");
|
||||
return res.status(200).send(obj);
|
||||
HomebrewModel.get({editId : req.params.id})
|
||||
.then((brew)=>{
|
||||
brew = _.merge(brew, req.body);
|
||||
brew.updatedAt = new Date();
|
||||
brew.save((err, obj)=>{
|
||||
if(err) throw err;
|
||||
return res.status(200).send(obj);
|
||||
})
|
||||
})
|
||||
});
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
return res.status(500).send("Error while saving");
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/api/remove/:id', (req, res)=>{
|
||||
|
||||
@@ -7,6 +7,7 @@ var HomebrewSchema = mongoose.Schema({
|
||||
editId : {type : String, default: shortid.generate, index: { unique: true }},
|
||||
title : {type : String, default : ""},
|
||||
text : {type : String, default : ""},
|
||||
authors : [String],
|
||||
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
updatedAt : { type: Date, default: Date.now},
|
||||
@@ -16,6 +17,40 @@ var HomebrewSchema = mongoose.Schema({
|
||||
|
||||
|
||||
|
||||
HomebrewSchema.methods.sanatize = function(full=false){
|
||||
const brew = this.toJSON();
|
||||
delete brew._id;
|
||||
delete brew.__v;
|
||||
if(full){
|
||||
delete brew.editId;
|
||||
}
|
||||
return brew;
|
||||
};
|
||||
|
||||
|
||||
HomebrewSchema.methods.increaseView = function(){
|
||||
return new Promise((resolve, reject) => {
|
||||
this.lastViewed = new Date();
|
||||
this.views = this.views + 1;
|
||||
this.save((err) => {
|
||||
if(err) return reject(err);
|
||||
return resolve(this);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
HomebrewSchema.statics.get = function(query){
|
||||
return new Promise((resolve, reject) => {
|
||||
Homebrew.find(query, (err, brews)=>{
|
||||
if(err || !brews.length) return reject('Can not find brew');
|
||||
return resolve(brews[0]);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
var Homebrew = mongoose.model('Homebrew', HomebrewSchema);
|
||||
|
||||
module.exports = {
|
||||
|
||||
Reference in New Issue
Block a user