Matteo Scandolo | e3ed016 | 2016-12-01 10:09:12 -0800 | [diff] [blame] | 1 | (function () { |
| 2 | 'use strict'; |
| 3 | |
| 4 | const request = require('superagent'); |
| 5 | const logger = require('../config/logger.js'); |
| 6 | |
| 7 | module.exports = function(app) { |
| 8 | |
| 9 | const proxyRequest = (req, res) => { |
| 10 | |
| 11 | const config = require('../config/config.js').xos; |
| 12 | // pick the correct method from superAgent |
| 13 | const makeReq = request[req.method.toLowerCase()]; |
| 14 | |
| 15 | // start the request |
| 16 | let sentReq = makeReq(`${config.host}:${config.port}${req.url}`); |
| 17 | |
| 18 | // if needed add a body to the request |
| 19 | if(req.method === 'POST' || req.method === 'PUT') { |
| 20 | sentReq = sentReq |
| 21 | .send(req.body) |
| 22 | } |
| 23 | |
| 24 | // extend with auth info |
| 25 | sentReq = sentReq |
| 26 | .set('x-csrftoken', req.headers['x-csrftoken'] || null) |
| 27 | .set('cookie', req.headers.cookie || null) |
| 28 | |
| 29 | // handle response |
| 30 | sentReq |
| 31 | .end((err, r) => { |
| 32 | if(err) { |
| 33 | logger.log('error', err); |
| 34 | return res.status(500).send(err); |
| 35 | } |
| 36 | logger.log('debug', r.status, r.body); |
| 37 | return res.status(r.status).type('json').send(r.body); |
| 38 | }); |
| 39 | }; |
| 40 | |
| 41 | app.all('/api/core', proxyRequest); |
| 42 | app.all('/api/core/*', proxyRequest); |
| 43 | app.all('/api/services', proxyRequest); |
| 44 | app.all('/api/services/*', proxyRequest); |
| 45 | app.all('/api/utility', proxyRequest); |
| 46 | app.all('/api/utility/*', proxyRequest); |
| 47 | }; |
| 48 | })(); |