-
Notifications
You must be signed in to change notification settings - Fork 2
/
rest-factory.js
41 lines (37 loc) · 952 Bytes
/
rest-factory.js
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
var JSONStream = require('JSONStream');
module.exports = function (model) {
return {
put: (req, res) => {
model.findById(req.body._id)
.then(page => {
if(!page) {
page = new model();
}
Object.assign(page, req.body);
return page.save();
})
.then(page => res.json(page._doc))
.catch(err => {
if (err.name == 'ValidationError') {
res.json(err.errors);
} else {
res.json({message: 'An error has occurred'});
}
});
},
getOne: (req, res) => {
model.findById(req.params.id)
.then(page => res.json(page));
},
'delete': (req, res) => {
model.findByIdAndRemove(req.params.id)
.then(() => res.status(204).end());
},
getAll: (req, res) => {
model.find()
.stream()
.pipe(JSONStream.stringify())
.pipe(res);
}
};
};