-
Notifications
You must be signed in to change notification settings - Fork 14
/
response.js
58 lines (48 loc) · 1.6 KB
/
response.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
const _ = require('lodash')
const logger = require('./logger')(__filename)
const displayConverter = require('./display_converter')
const { CORRELATION_ID } = require('@govuk-pay/pay-js-commons').logging.keys
const ERROR_MESSAGE = 'There is a problem with the payments platform'
const ERROR_VIEW = 'error'
function response (req, res, template, data = {}) {
let convertedData = displayConverter(req, data, template)
render(req, res, template, convertedData)
}
function errorResponse (req, res, msg, status = 500) {
if (!msg) msg = ERROR_MESSAGE
let correlationId = req.correlationId
if (typeof msg !== 'string') {
msg = 'Please try again or contact support team.'
}
let data = { 'message': msg }
const errorMeta = {
'status': status,
'error_message': msg
}
errorMeta[CORRELATION_ID] = correlationId
if (status === 500) {
logger.error('An error has occurred. Rendering error view', errorMeta)
} else {
logger.info('An error has occurred. Rendering error view', errorMeta)
}
res.setHeader('Content-Type', 'text/html')
res.status(status)
render(req, res, ERROR_VIEW, data)
}
function render (req, res, template, data) {
if (process.env.NODE_ENV !== 'production' && _.get(req, 'headers.accept') === 'application/json') {
res.setHeader('Content-Type', 'application/json')
res.json(data)
} else {
res.render(template, data)
}
}
function healthCheckResponse (accept, res, data) {
res.setHeader('Content-Type', 'application/json')
res.json(data)
}
module.exports = {
response: response,
healthCheckResponse: healthCheckResponse,
renderErrorView: errorResponse
}