This repository has been archived by the owner on Aug 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
179 lines (159 loc) · 5.62 KB
/
server.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// API VERSION NUMBER
const API_VERSION = '1.3.4';
/** ************* SET UP ************** */
const fs = require('fs'); // for configuration file
const express = require('express'); // express
const compression = require('compression'); // gzip or deflate compression for page loading
const helmet = require('helmet'); // security for production
const cors = require('cors'); // allow using CORS
/** ************* LOCAL SERVICES ************** */
const RequestService = require('./services/request');
const Database = require('./services/database');
const Logger = require('./services/logger');
const Config = require('./config/app-config');
/** ************* CONFIG ************** */
const app = express(); // create our app w/ express
app.use(compression()); // compress all requests
app.use(helmet()); // security for well-known web vulnerabilities
app.use(cors()); // use cors to allow cross requests
/** ************* DB INIT ************** */
Logger.verbose('Server - Initializing caching database... !');
Database.init();
Logger.verbose('Server - Caching database initialized !');
/** ************* LISTEN ************** */
const port = Config.SERVER_PORT || 8081;
app.listen(port);
Logger.info(`Server - Listening on port ${port} with HTTP`);
/** ************* MODEL ************** */
let routes = {};
fs.readFile(`${__dirname}/config/routes.json`, 'utf8', (err, data) => {
if (err) {
Logger.error('Server - Routes config file not found or not readable (/config/routes.json)');
process.exit(1);
}
routes = JSON.parse(data);
});
/** ************* ROUTES ************** */
/** ********* API ********** */
/**
* Root path of the Overwatch API, listing main routes and link to swagger
*/
app.get('/', (req, res) => {
Logger.info('Server - Displaying root path of the API');
res.status(200).send({
statusCode: 200,
message: 'Overwatch API root path',
version: API_VERSION,
routes: {
'/player': 'Get data about a player',
'/heroes': 'Get data about Overwatch heroes',
'/hero': 'Get detailed data about a specific Overwatch hero',
},
swagger: Config.SWAGGER_URL,
});
});
/**
* Get data about a player (all, playerInfo, heroes, ...).
* Optional params : ?platform=<pc/xbl/psn>
*/
app.get([
'/player/:battletag',
'/player/:battletag/:request',
'/player/:battletag/:request/:options',
], (req, res) => {
// Initialize options
const options = {
host: Config.BLIZZARD_HOST,
path: Config.CAREER_PATH,
};
// default platform
let requestPlatform = 'pc';
if (req.query && req.query.platform) {
requestPlatform = req.query.platform;
}
// if incorrect platform
if (['pc', 'psn', 'xbl', 'nintendo-switch'].indexOf(requestPlatform) === -1) {
Logger.error(`Server - Incorrect requested platform : ${requestPlatform}`);
res.status(400).send({
statusCode: 400,
message: 'Error : incorrect requested platform',
});
} else {
Logger.info(`Server - Valid requested platform : ${requestPlatform}. Loading data for player ${req.params.battletag}...`);
options.params = `${requestPlatform}/${encodeURI(req.params.battletag)}`;
// do the routing process for player
Logger.info('Server - Searching for the player route config corresponding to request...');
const routeConfig = RequestService.findPlayerRouteConfig(req, routes.player);
// send the request
Logger.info('Server - Sending API request to Blizzard player page...');
RequestService.sendApiRequest(res, options, routeConfig, 'Player not found');
}
});
/**
* Get global data about heroes (list, by role, ..)
*/
app.get([
'/heroes',
'/heroes/:request',
], (req, res) => {
// initialize options
const options = {
host: Config.BLIZZARD_HOST,
path: Config.HEROES_PATH,
params: '',
};
// choose the right route
let routeConfig = false;
// if no request, display all heroes
if (!req.params.request) {
Logger.info('Server - No specific request for heroes route. Loading route config for all heroes...');
routeConfig = routes.heroes['/'];
} else {
// else, display the request role
Logger.info(`Server - Specific request for heroes route : ${req.params.request}. Loading route config for specific hero...`);
routeConfig = JSON.stringify(routes.heroes['/role']);
routeConfig = routeConfig.replace(':role', req.params.request);
routeConfig = JSON.parse(routeConfig);
}
// send the request
Logger.info('Server - Sending API request to Blizzard heroes page...');
RequestService.sendApiRequest(res, options, routeConfig, 'Heroes not found');
});
/**
* Get data about a specific hero (name, bio, ...)
*/
app.get([
'/hero/:request',
], (req, res) => {
// initialize options
const options = {
host: Config.BLIZZARD_HOST,
path: Config.HEROES_PATH,
params: req.params.request,
};
// load the route config
const routeConfig = routes.hero['/'];
// send the request
RequestService.sendApiRequest(res, options, routeConfig, 'Hero not found');
});
/** ********* ERRORS ********** */
/**
* Handle 404 errors
*/
app.use((req, res) => {
Logger.error(`Server - Invalid route provided, sending 404 error... URL : ${req.url}`);
res.status(404).send({
statusCode: 404,
message: `API Version : ${API_VERSION} | Error, no route found for given arguments`,
});
});
/**
* Handle 500 errors
*/
app.use((error, req, res) => {
Logger.error(`Server - Internal server error. URL : ${req.url}. Error : ${JSON.stringify(error)}`);
res.status(500).send({
statusCode: 500,
message: `API Version : ${API_VERSION} | Interval server error, contact the administrator or report the issue on GitHub (https://github.com/TeKrop/overwatch-api/issues)`,
});
});