-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
executable file
·75 lines (67 loc) · 1.79 KB
/
app.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
'use strict';
const express = require('express');
const app = express();
const router = express.Router();
const jwt = require('jsonwebtoken');
const marklogic = require('marklogic');
const settings = require('./settings');
const db = marklogic.createDatabaseClient(settings.connection);
const qb = marklogic.queryBuilder;
app.set('port', 8080);
app.use('/', router);
const authenticate = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
jwt.verify(token, 's3cr3t', (error, decoded) => {
if (error) {
console.log(error);
res.sendStatus(401);
} else {
req.username = decoded.username;
next();
}
});
} else {
res.status(403).send({message: 'No token provided.'});
}
};
const characters = (req, res) => {
if (req.username) {
db.documents.query(
qb.where(
qb.directory('/character/')
).slice(0,100)
).result()
.then((response) => {
const characterNames = response.map((character) => {
return character.content.name;
});
res.json(characterNames);
})
.catch((error) => {
console.log(error);
});
}
};
const vehicles = (req, res) => {
db.documents.query(
qb.where(
qb.directory('/vehicle/')
).slice(0,100)
).result()
.then((response) => {
const vehicleNames = response.map((vehicle) => {
return vehicle.content.name;
});
res.json(vehicleNames);
})
.catch((error) => {
console.log(error);
});
};
router.route('/api/characters').get(authenticate, characters);
router.route('/api/vehicles').get(vehicles);
app.listen(app.get('port'), () => {
console.log('Magic happens on port ' + app.get('port') + ' "/api/characters" or "/api/vehicles".');
});