index.js
1.59 KB
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
/**
* API Server
*/
const express = require('express');
const uniqid = require('uniqid');
const logger = require('tektrans-logger');
const config = require('../config');
const requestLogger = require('./middlewares/request-logger');
const routerConfig = require('./router-config');
const routerMatrix = require('./router-matrix');
const routerServices = require('./router-services');
const routerProducts = require('./router-products');
const routerRemoteProducts = require('./router-remote-products');
const routerLocations = require('./router-locations');
const app = express();
function isConfigured() {
return Boolean(config && config.apiserver && config.apiserver.apikey && config.apiserver.port);
}
function isValidApikey(apikey) {
return isConfigured() && (config.apiserver.apikey === apikey);
}
function needValidApikey(req, res, next) {
if (isValidApikey(req.params.apikey)) {
next();
} else {
res.end('INVALID_APIKEY');
}
}
if (isConfigured()) {
app.listen(config.apiserver.port, () => {
logger.info('API-SERVER listening', { port: config.apiserver.port });
});
}
// initialize xid
app.use((req, res, next) => {
res.locals.xid = uniqid();
next();
});
app.use(requestLogger);
app.use('/apikey/:apikey', needValidApikey);
app.use('/apikey/:apikey/config', routerConfig);
app.use('/apikey/:apikey/matrix', routerMatrix);
app.use('/apikey/:apikey/services', routerServices);
app.use('/apikey/:apikey/products', routerProducts);
app.use('/apikey/:apikey/remote-products', routerRemoteProducts);
app.use('/apikey/:apikey/locations', routerLocations);