-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
110 lines (90 loc) · 3.15 KB
/
index.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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
'use strict';
let _model = null;
module.exports = class Crud {
static model (model) {
_model = model;
};
static list (req, res) {
let limit = req.query._limit;
delete req.query._limit;
let skip = req.query._skip;
delete req.query._skip;
let sort = req.query._sort;
delete req.query._sort;
let count = req.query._count;
delete req.query._count;
let params = req.query || {};
_model.find(params)
.limit(limit)
.skip(skip)
.sort(sort)
.exec((err, data) => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
if (!count) {
return res.status(200).json({ success: true, data: data });
}
_model.count(params, (err, count) => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
return res.status(200).json({ success: true, data: data, count: count });
});
});
};
static create (req, res) {
let data = new _model(req.body);
data.save(err => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
return res.status(200).json({ success: true, data: data });
});
};
static findById (req, res) {
_model.find({ _id: req.params.id }, (err, data) => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
if (!data) {
return res.status(404).json({ success: false, message: 'Not found' });
}
return res.status(200).json({ success: true, data: data });
});
};
static update (req, res) {
let query = { _id: req.params.id };
_model.find(query, (err, data) => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
if (!data) {
return res.status(404).json({ success: false, message: 'Not found' });
}
_model.update(query, { $set: req.body }, err => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
return res.status(200).json({ success: true });
});
});
};
static delete (req, res) {
let query = { _id: req.params.id };
_model.find(query, (err, data) => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
if (!data) {
return res.status(404).json({ success: false, message: 'Not found' });
}
_model.remove(query, err => {
if (err) {
return res.status(500).json({ success: false, message: err });
}
return res.status(200).json({ success: true });
});
});
};
};