This repository has been archived by the owner on Jan 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
87 lines (79 loc) · 2.63 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
76
77
78
79
80
81
82
83
84
85
86
87
const { helpersConfig } = require("./config");
const cookieParser = require("cookie-parser");
const sanitize = require('sanitize');
const express = require("express");
const app = express();
const ramAPI = require('./models/ramAPI');
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(sanitize.middleware);
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Content-Type", "application/json");
next();
});
router = express.Router();
// /characters
router.get('/characters', async (req, res) => {
const page = req.query.page !== undefined ? req.query.page : 1;
await ramAPI.getChars(page)
.then(payload => {
res.statusCode = 200;
res.send(JSON.stringify({ data: payload.data }))
})
.catch(err => {
console.log(err);
res.send(JSON.stringify(false))
});
});
// res.status(201).json
// /characters/search
router.get('/characters/search', async (req, res) => {
const filterOptions = ['name', 'status', 'species', 'type', 'gender'];
const filters = {};
for (const filterOption of filterOptions) {
if (undefined !== req.query[filterOption]) {
filters[filterOption] = req.query[filterOption];
}
}
const strFilters = ramAPI.uriEncodeArray(filters);
const page = req.query.page !== undefined ? req.query.page : 1;
await ramAPI.search(strFilters, page)
.then(payload => {
res.statusCode = 200;
res.send(JSON.stringify({ data: payload.data }))
})
.catch(err => {
console.log(err);
res.send(JSON.stringify(false))
});
});
// /characters/{id}
router.get('/characters/:id(\\d+)', async (req, res) => {
if (null === `${req.params.id}`.match(/^\d+$/)) {
res.statusCode = 400;
return res.send({
"Message": "ID parameter must be a valid integer."
});
}
await ramAPI.getCharacter(req.params.id)
.then(payload => {
res.statusCode = 200;
res.send(JSON.stringify({ data: payload.data }))
})
.catch(err => {
console.log(err);
res.send(JSON.stringify(false))
});
});
app.use('/api/v1', router);
if (helpersConfig.nodeEnv === "production") {
app.listen(helpersConfig.appPort);
} else {
app.listen(helpersConfig.appPort, () => {
const url = `http://127.0.0.1:${helpersConfig.appPort}`;
console.log(`Listening on ${url}`);
});
}