UNPKG

5.68 kBJavaScriptView Raw
1/*****
2 License
3 --------------
4 Copyright © 2017 Bill & Melinda Gates Foundation
5 The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
11 Contributors
12 --------------
13 This is the official list of the Mojaloop project contributors for this file.
14 Names of the original copyright holders (individuals or organizations)
15 should be listed with a '*' in the first column. People who have
16 contributed from an organization can be listed under the organization
17 that actually holds the copyright for their contributions (see the
18 Gates Foundation organization for an example). Those individuals should have
19 their names indented and be marked with a '-'. Email address can be added
20 optionally within square brackets <email>.
21
22 * Gates Foundation
23 - Name Surname <name.surname@gatesfoundation.com>
24
25 * ModusBox
26 - Neal Donnan <neal.donnan@modusbox.com>
27 - Rajiv Mothilal <rajiv.mothilal@modusbox.com>
28
29 --------------
30 ******/
31
32'use strict'
33
34const Factory = require('./factory')
35const Errors = require('./enums').FSPIOPErrorCodes
36
37const getReplyToFromRequestHeaders = (request) => {
38 return (request.headers && request.headers['fspiop-source']) ? request.headers['fspiop-source'] : null
39}
40
41const createFSPIOPErrorFromErrorResponse = (request, response) => {
42 const fspiopError = ((response, request) => {
43 switch (response.output.statusCode) {
44 case 400:
45 return Errors.CLIENT_ERROR
46 case 404:
47 {
48 const matches = findMatches(request)
49
50 if (matches.length > 0) {
51 const allowedHeaderValues = getAllowHeaders(matches)
52 response.message = ''
53 response.output.headers.Allow = allowedHeaderValues
54 return Errors.METHOD_NOT_ALLOWED
55 } else {
56 return Errors.UNKNOWN_URI
57 }
58 }
59 case 415:
60 return Errors.MALFORMED_SYNTAX
61
62 default:
63 return Errors.INTERNAL_SERVER_ERROR
64 }
65 })(response, request)
66
67 return Factory.createFSPIOPError(fspiopError, response.message, response.stack, getReplyToFromRequestHeaders(request))
68}
69
70const findMatches = (request) => {
71 const server = request.server
72 const path = request.path
73 const matches = []
74 const methods = ['get', 'post', 'put', 'patch', 'delete']
75
76 for (const i in methods) {
77 const match = server.match(methods[i], path)
78 if (match != null) {
79 const data = { method: match.method }
80 matches.push(data)
81 }
82 }
83
84 return matches
85}
86
87const getAllowHeaders = (matches) => {
88 let headers = ''
89
90 for (const i in matches) {
91 const method = matches[i].method
92
93 if (headers === '') {
94 headers += method
95 } else {
96 headers += ',' + method
97 }
98 }
99
100 return headers
101}
102
103const reformatError = (request, response) => {
104 if (!response.output) {
105 response.output = {}
106 }
107
108 let fspiopError
109 if (response.isJoi) {
110 const replyTo = getReplyToFromRequestHeaders(request)
111 fspiopError = Factory.createFSPIOPErrorFromJoiError(request.response.details[0], response, replyTo)
112 } else if (response.name === 'FSPIOPError') {
113 fspiopError = response
114 } else {
115 fspiopError = createFSPIOPErrorFromErrorResponse(request, response)
116 }
117
118 response.output.payload = fspiopError.toApiErrorObject()
119 if (fspiopError.httpStatusCode) {
120 response.output.statusCode = fspiopError.httpStatusCode
121 }
122
123 if (!response.output.statusCode) {
124 response.output.statusCode = 500
125 }
126}
127
128/**
129 * Function to be used to handle the 'onPreResponse' Hapi server extension.
130 * This reformats the standard Boom and Joi error output to a compliant error
131 * format as per section 7.6 of "API Definition v1.0.docx".
132 *
133 * @param request the http request
134 * @param reply
135 * @returns {boolean|reply.continue|continue|((key?: IDBValidKey) => void)}
136 */
137const onPreResponse = (request, reply) => {
138 const response = request.response
139 if (response instanceof Error || response.isBoom) {
140 reformatError(request, response)
141 }
142
143 return reply.continue
144}
145
146/**
147 * Function to be used to handle the 'validateIncomingErrorCode' Hapi server extension.
148 * This validates the error is a FSPIOPError and that it contains a valid error code
149 * format as per section 7.6 of "API Definition v1.0.docx".
150 *
151 * @param request the http request
152 * @param h
153 * @returns {boolean|h.continue|continue|((key?: IDBValidKey) => void)}
154 */
155const validateIncomingErrorCode = (request, h) => {
156 const incomingErrorCode = request.payload.errorInformation.errorCode
157 try {
158 if (Factory.validateFSPIOPErrorCode(incomingErrorCode).code === incomingErrorCode) {
159 return h.continue
160 }
161 } catch (err) {
162 try {
163 if (Factory.validateFSPIOPErrorGroups(incomingErrorCode)) {
164 return h.continue
165 }
166 } catch (err) {
167 const onPreHandlerApiErrorObject = Factory.createFSPIOPError(Errors.VALIDATION_ERROR, `The incoming error code: ${incomingErrorCode} is not a valid mojaloop specification error code`).toApiErrorObject()
168 return h
169 .response(onPreHandlerApiErrorObject)
170 .code(400)
171 .takeover()
172 }
173 }
174}
175
176module.exports = {
177 validateIncomingErrorCode,
178 onPreResponse,
179 createFSPIOPErrorFromErrorResponse,
180 getAllowHeaders,
181 findMatches
182}