Commit 18d4b0fd authored by Stepheno's avatar Stepheno

(feat) proxy

parent 3d6ddb62
......@@ -17,7 +17,7 @@ async function execute() {
jsonServer.start({
host: program.host,
port: program.port,
proxy: program.port,
proxy: program.proxy,
folder: program.folder,
keyFile: program.keyFile,
certFile: program.certFile,
......
......@@ -8,10 +8,11 @@ const path = require('path');
const fs = require('fs');
const http = require('http');
const https = require('https');
const httpProxy = require('http-proxy');
const proxyServer = httpProxy.createProxyServer({});
let jsonPath;
function handler(request, response) {
function handler(jsonPath, proxy) {
return function (request, response) {
const {url} = request;
if (url === '/favicon.ico') {
......@@ -20,9 +21,25 @@ function handler(request, response) {
return;
}
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST,GET,PUT,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type,Access-Token',
};
if (proxy) {
const target = proxy.startsWith('http') ? proxy : `http://${proxy}`;
console.log(`proxy: ${target}${url}`)
Object.entries(headers).forEach(([key, val]) => response.setHeader(key, val));
return proxyServer.web(request, response, { target }, err => {
console.log(err);
})
}
const pos = url.indexOf('?');
const fileUri = pos < 0 ? url : url.substring(0, pos);
console.log(request.method, fileUri);
console.log('mook: ', request.method, fileUri);
const filePath = path.join(jsonPath, fileUri);
let content, targetFile;
......@@ -39,12 +56,6 @@ function handler(request, response) {
}
}
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST,GET,PUT,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type,Access-Token',
};
if (content) {
response.writeHead(200, headers);
......@@ -56,13 +67,13 @@ function handler(request, response) {
}))
}
response.end();
}
}
exports.start = function (options) {
return new Promise((resolve, reject) => {
const {port, host, proxy, folder, keyFile, certFile} = options;
jsonPath = path.resolve(folder);
const jsonPath = path.resolve(folder);
if (fs.existsSync(jsonPath)) {
let sslOpts;
if(keyFile && certFile){
......@@ -77,7 +88,7 @@ exports.start = function (options) {
}
}
const server = sslOpts ? https.createServer(sslOpts, handler) : http.createServer(handler);
const server = sslOpts ? https.createServer(sslOpts, handler(jsonPath, proxy)) : http.createServer(handler(jsonPath, proxy));
server.on('error', (err) => {
reject(err.message);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment