-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (82 loc) · 2.69 KB
/
Copy pathindex.js
File metadata and controls
92 lines (82 loc) · 2.69 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
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
import bodyParser from 'body-parser';
import { create as createDomain } from 'domain';
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import YAML from 'yamljs';
import config from './config.js';
import apiRoutes from './lib/api.js';
import { getLogger } from './lib/logger.js';
import adapterDetails from './src/adapterDetails.js';
const swaggerDocument = YAML.load('./reference/sync-adapter.v1.yaml');
const logger = getLogger({ module: 'index.js' });
const app = express();
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
let reqId = 0;
app.use((req, res, next) => {
const externalSystem = req.headers[adapterDetails.getExternalSystemIdentificationHeaderName()];
if (req.path === '/api/health') {
next();
return;
}
req.reqId = reqId++;
if (externalSystem) {
logger.action(
req.method +
' [' +
req.reqId +
'] ' +
req.path +
' (Master: ' +
req.headers.x_master_uri +
', ES: ' +
externalSystem +
')'
);
} else {
logger.action(req.method + ' [' + req.reqId + '] ' + req.path + ' (Master: ' + req.headers.x_master_uri + ')');
}
next();
});
// error handling
app.use(function (req, res, next) {
// create a domain for this request
let domain = createDomain();
// handle errors on this domain
domain.on('error', function (err) {
logger.error('[' + req.reqId + '] DOMAIN ERROR CAUGHT');
console.dir(err);
try {
try {
// attempt to use Express error route
next(err);
} catch (error) {
// if Express error route failed, try plain Node response
logger.error('[' + req.reqId + '] Express error mechanism failed.\n', error.stack);
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Server error.');
}
} catch (error) {
logger.error('[' + req.reqId + '] Unable to send 500 response.\n', error.stack);
}
});
// add the request and response objects to the domain
domain.add(req);
domain.add(res);
// execute the rest of the request chain in the domain
domain.run(next);
});
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/', apiRoutes);
app.listen(config.port, err => {
if (err) {
return logger.error('Sync adapter: something bad happened', err);
}
logger.info(`Sync adapter is listening on ${config.port}`);
return true;
});