-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroutes.js
97 lines (89 loc) · 3.04 KB
/
routes.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
const express = require('express');
const jwt = require('jsonwebtoken');
const db = require('./db');
const router = express.Router();
const maxPageSize = 100;
const secret = process.env.APISECRET;
router.use((req, res, next) => {
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(403).send({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided'
});
}
});
router.get('/bands', (req, res) => {
let params = {};
if (req.query.name)
params.name = new RegExp(["^", ".*", req.query.name.replace("_", " "), ".*", "$"].join(""), "i");
if (req.query.country)
params.country = new RegExp(["^", req.query.country.replace("_", " "), "$"].join(""), "i");
if (req.query.location)
params.location = new RegExp(["^", req.query.location.replace("_", " "), "$"].join(""), "i");
if(req.query.genre)
params.genre = req.query.genre.replace("_", ".").toLowerCase();
let limit = parseInt(req.query.limit, 10);
if (isNaN(limit) || limit > maxPageSize) {
limit = maxPageSize;
} else if (limit < 1) {
limit = 1;
}
let page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1) {
page = 1;
}
db.get().collection("bands").find(params).skip((page - 1) * limit).limit(limit).sort({ name: 1 }).toArray((err, result) => {
if (!err) {
let resp;
if (req.query.name) {
let bestMatch = [];
let others = [];
let rg = new RegExp(["^", req.query.name.replace("_", " "), ".*", "$"].join(""), "i");
result.forEach(function (b) {
if (b.name.match(rg)) {
bestMatch.push(b);
} else {
others.push(b);
}
});
resp = { "data": bestMatch.concat(others) };
}
else {
resp = { "data": result };
}
res.status(200).send(resp);
} else {
res.status(500).send(err);
}
});
});
router.get('/countries', (req, res) => {
if (!req.query.genre) {
res.status(500).send({ "message": "Pass a genre name as query parameter" });
} else {
let genre = req.query.genre.replace("_", ".").toLowerCase();
db.get().collection(genre).distinct(
"country",
{}, // query object
(function (err, docs) {
if (err) {
res.status(500).send(err);
}
if (docs) {
res.status(200).send(docs.sort());
}
})
);
}
});
module.exports = router;