-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-middleware.js
96 lines (91 loc) · 2.44 KB
/
api-middleware.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
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('./db.json');
let db = low(adapter);
const moment = require('moment');
let _ = require('lodash');
const METHODS = {
tours: 'tours',
news: 'news',
gallery: 'gallery',
years: 'years',
music: 'music',
press: 'press'
};
module.exports = (req, res, next) => {
let result = { status: 'nothing found' };
let path = req.path;
let [, section = false, path1 = false, id = false] = path.split('/');
path1 = !_.isNaN(Number(path1)) ? Number(path1) : path1;
if (!section) {
return res.json(result);
}
let prom;
switch (section) {
case METHODS.press:
prom = Promise.resolve(db.get(METHODS.press).value());
break;
case METHODS.tours:
if (path1) {
prom = Promise.resolve(db.get(METHODS.tours)
.filter((item) => moment(item.date).year() === path1)
.value());
} else {
prom = Promise.resolve(db.get(METHODS.tours).value());
}
break;
case METHODS.news:
if (path1) {
prom = Promise.resolve(db.get(METHODS.news)
.filter((item) => moment(item.date).year() === path1)
.value());
} else {
prom = Promise.resolve(db.get(METHODS.news).value());
}
break;
case METHODS.gallery:
if (id) {
prom = Promise.resolve(db.get(METHODS.gallery)
.find({ date: Number(id) })
.value());
} else if (path1) {
prom = Promise.resolve(db.get(METHODS.gallery)
.filter((item) => moment(item.date).year() === path1)
.value());
} else {
prom = Promise.resolve(db.get(METHODS.gallery).value());
}
break;
case METHODS.years:
if (!path1) {
prom = Promise.resolve([]);
break;
}
prom = Promise.resolve(db.get(METHODS[path1])
.map(({ date }) => moment(date).year())
.concat(moment().year())
.uniq()
.sortBy((year) => year)
.value());
break;
case METHODS.music:
if (path1) {
prom = Promise.resolve(db.get(METHODS.music)
.find({ urlName: path1 })
.value());
} else {
prom = Promise.resolve(db.get(METHODS.music)
.value());
}
break;
default:
return next();
}
prom
.then((collection) => {
res.json(collection);
})
.catch((err) => {
console.log('error', err);
});
};