(appId, promiseHandler)
| 135 | // Express handlers should never throw; if a promise handler throws we |
| 136 | // just treat it like it resolved to an error. |
| 137 | function makeExpressHandler(appId, promiseHandler) { |
| 138 | return function (req, res, next) { |
| 139 | try { |
| 140 | const url = maskSensitiveUrl(req); |
| 141 | const body = Object.assign({}, req.body); |
| 142 | const method = req.method; |
| 143 | const headers = req.headers; |
| 144 | log.logRequest({ |
| 145 | method, |
| 146 | url, |
| 147 | headers, |
| 148 | body, |
| 149 | }); |
| 150 | promiseHandler(req) |
| 151 | .then( |
| 152 | result => { |
| 153 | if (!result.response && !result.location && !result.text) { |
| 154 | log.error('the handler did not include a "response" or a "location" field'); |
| 155 | throw 'control should not get here'; |
| 156 | } |
| 157 | |
| 158 | log.logResponse({ method, url, result }); |
| 159 | |
| 160 | var status = result.status || 200; |
| 161 | res.status(status); |
| 162 | |
| 163 | if (result.headers) { |
| 164 | Object.keys(result.headers).forEach(header => { |
| 165 | res.set(header, result.headers[header]); |
| 166 | }); |
| 167 | } |
| 168 | |
| 169 | if (result.text) { |
| 170 | res.send(result.text); |
| 171 | return; |
| 172 | } |
| 173 | |
| 174 | if (result.location) { |
| 175 | res.set('Location', result.location); |
| 176 | // Override the default expressjs response |
| 177 | // as it double encodes %encoded chars in URL |
| 178 | if (!result.response) { |
| 179 | res.send('Found. Redirecting to ' + result.location); |
| 180 | return; |
| 181 | } |
| 182 | } |
| 183 | res.json(result.response); |
| 184 | }, |
| 185 | error => { |
| 186 | next(error); |
| 187 | } |
| 188 | ) |
| 189 | .catch(e => { |
| 190 | log.error(`Error generating response. ${inspect(e)}`, { error: e }); |
| 191 | next(e); |
| 192 | }); |
| 193 | } catch (e) { |
| 194 | log.error(`Error handling request: ${inspect(e)}`, { error: e }); |
no test coverage detected