forked from pelias/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendJSON.js
52 lines (40 loc) · 1.32 KB
/
sendJSON.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
const _ = require('lodash');
const es = require('elasticsearch');
const logger = require( 'pelias-logger' ).get( 'api' );
const PeliasParameterError = require('../sanitizer/PeliasParameterError');
const PeliasTimeoutError = require('../sanitizer/PeliasTimeoutError');
function isParameterError(error) {
return error instanceof PeliasParameterError;
}
function isTimeoutError(error) {
return error instanceof PeliasTimeoutError ||
error instanceof es.errors.RequestTimeout;
}
function isElasticsearchError(error) {
const knownErrors = [ es.errors.NoConnections,
es.errors.ConnectionFault ];
return knownErrors.some(function(esError) {
return error instanceof esError;
});
}
function sendJSONResponse(req, res, next) {
// do nothing if no result data set
const geocoding = _.get(res, 'body.geocoding');
if (!_.isPlainObject(geocoding)) {
return next();
}
const errors = geocoding.errors || [];
const errorCodes = errors.map(function(error) {
if (isParameterError(error)) {
return 400;
} else if (isTimeoutError(error) || isElasticsearchError(error)) {
return 502;
} else {
return 500;
}
});
const statusCode = Math.max(200, ...errorCodes);
// respond
return res.status(statusCode).json(res.body);
}
module.exports = sendJSONResponse;