-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.js
93 lines (77 loc) · 2.23 KB
/
controller.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
const {
readFile,
writeFile,
randomId,
findDataById,
sort,
pagination,
searching,
resSuccess,
resError,
resNotFound
} = require('./helper.js');
module.exports = {
getAll: (req, res) => {
try {
const { search, sorting, limit, skip } = req.query;
const [searchBy, name] = search ? search.split('-') : [null, null];
const [field, sortBy] = sorting ? sorting.split('-') : [null, null];
let data = readFile(req.path);
// SEARCH FUNC
if (name && searchBy) data = data.filter(str => searching(str[searchBy], name))
// SORT FUNC
if (field && sortBy) data = sort(data, field, sortBy);
// LIMIT FUNC
if (limit || skip) data = pagination(data, limit, skip)
resSuccess({ req, res, data })
} catch (err) {
resError({ req, res, err });
}
},
getByID: (req, res) => {
try {
const data = findDataById(req.path, req.params.id);
if (!data) return resNotFound(req, res);
resSuccess({ req, res, data })
} catch (err) {
resError({ req, res, err });
}
},
create: (req, res) => {
try {
let db = readFile(req.path);
const data = { id: randomId(), ...req.body, create_at: new Date() };
db.unshift(data);
writeFile(req.path, db);
resSuccess({ req, res, data, msg: `data has been create!` })
} catch (err) {
resError({ req, res, err });
}
},
update: (req, res) => {
try {
let db = readFile(req.path);
let row = findDataById(req.path, req.params.id);
if (!row) return resNotFound(req, res);
data = { ...row, ...req.body };
const idx = db.findIndex((p) => p.id === req.params.id);
db[idx] = data;
writeFile(req.path, db);
resSuccess({ req, res, data, msg: `data has been updated!` })
} catch (err) {
resError({ req, res, err });
}
},
del: (req, res) => {
try {
let db = readFile(req.path);
const data = findDataById(req.path, req.params.id);
if (!data) return resNotFound(req, res);
db = db.filter((p) => p.id !== req.params.id);
writeFile(req.path, db);
resSuccess({ req, res, data, msg: `data has been deleted!` })
} catch (err) {
resError({ req, res, err });
}
},
}