-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetupProxy.js
More file actions
68 lines (59 loc) · 2.11 KB
/
setupProxy.js
File metadata and controls
68 lines (59 loc) · 2.11 KB
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
59
60
61
62
63
64
65
66
67
68
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
const http = require('http');
const https = require('https');
const express = require('express');
require('dotenv').config({ path: `./.env.${process.env.DEV_ENV}` });
function handleRequest(requestOptions) {
return (req, res) => {
const requestBody = req.body;
let resData = '';
requestOptions.path = req.originalUrl;
requestOptions.method = req.method;
if (req.header('Authorization')) requestOptions.headers.Authorization = req.header('Authorization');
const protocol = requestOptions.port === 443 ? https : http;
const postReq = protocol.request(requestOptions, (postRes) => {
postRes.on('data', (chunk) => {
resData += chunk;
});
postRes.on('end', () => {
if (postRes.statusCode >= 400) {
try {
const jsonResponse = JSON.parse(resData);
res.status(postRes.statusCode).json(jsonResponse);
} catch (e) {
res.status(postRes.statusCode).json({
error: resData
});
}
} else {
res.send(resData);
}
});
});
postReq.on('error', (err) => {
console.error(err.message);
res.status(500).json({
error: 'Internal Server Error'
});
});
if (requestBody && req.method === 'POST') {
postReq.write(JSON.stringify(requestBody));
}
postReq.end();
};
}
module.exports = function (app) {
app.use(express.json());
app.use(
['/v2/register_user', '/v2/register_device', '/v2/access_token/issue'],
handleRequest({
host: process.env.REACT_APP_PROXY_AS_URI,
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
})
);
};