metamaps--metamaps/apiProxyMiddleware.js

34 lines
1 KiB
JavaScript
Raw Normal View History

2018-03-11 20:24:57 +00:00
/*
This file takes appropriate requests from our UI client
and pipes them through to the API, proxying the response
back to the client. To do this, it needs to pass
the _Metamaps_session cookie in particular,
in order to make authorized requests
*/
const request = require('request')
2018-03-11 20:24:57 +00:00
const { API_PROTOCOL, API_HOST } = process.env
const API_URL = `${API_PROTOCOL}://${API_HOST}`
2018-03-04 02:49:11 +00:00
function apiProxyMiddleware (req, res, next) {
2018-03-09 20:53:46 +00:00
// TODO: tidy this up!
2018-03-10 00:17:56 +00:00
if (!(req.xhr || req.headers['content-type'] === 'application/json' || req.originalUrl.indexOf('.json') > -1 || req.method !== 'GET')) {
2018-03-04 02:49:11 +00:00
return next()
}
const method = req.method.toLowerCase()
req.pipe(
2018-03-11 20:24:57 +00:00
request[method](API_URL + req.originalUrl, {
2018-03-04 02:49:11 +00:00
headers: {
...req.headers,
2018-03-06 04:27:38 +00:00
cookie: `_Metamaps_session=${req.cookies._Metamaps_session}`,
2018-03-11 20:24:57 +00:00
host: API_HOST
2018-03-04 02:49:11 +00:00
},
followRedirect: false
})
)
2018-03-06 04:27:38 +00:00
.on('error', (err) => console.log(err))
2018-03-04 02:49:11 +00:00
.pipe(res)
}
module.exports = apiProxyMiddleware