Skip to content

Instantly share code, notes, and snippets.

@tomek-f
Created June 25, 2018 19:06
Show Gist options
  • Save tomek-f/ffeffd36ef33d30bd03a1ada8b15f167 to your computer and use it in GitHub Desktop.
Save tomek-f/ffeffd36ef33d30bd03a1ada8b15f167 to your computer and use it in GitHub Desktop.
const http = require('http');
const { parse: urlParse } = require('url');
const { parse: querystringParse } = require('querystring');
const log = require('fancy-log');
const chalk = require('chalk');
const env = require('minimist')(process.argv.slice(2));
const getUrlVar = (where, item) => querystringParse(urlParse(where).query)[item];
const line = '-'.repeat(80);
// destructuring & default
const {
hostname = 'romantycylekkichobyczajow.pl',
port = 80,
serverPort = 1337,
method = 'get',
requiredUrl = '/wp-json/wp/v2/',
requiredContentType = 'application/json',
} = env;
log(chalk.yellow(`running localhost:${serverPort}`));
log(chalk.yellow('getting json(p) data'));
log(chalk.yellow(`from ${hostname}:${port}${requiredUrl}...`));
log(chalk.yellow(`visit localhost:${serverPort}${requiredUrl}...`));
log(chalk.gray(line));
function onRequest(clientReq, clientRes) {
const options = {
hostname,
port,
path: clientReq.url,
method,
};
const proxy = http.request(options, function (res) {
const contentType = res.headers['content-type'];
const url = clientReq.url;
if (!url.includes(requiredUrl) || !contentType.includes(requiredContentType)) {
res.pipe(clientRes, { end: true });
log(chalk.gray(`skip (${res.headers['content-type']}) ${clientReq.url}`));
return;
}
let body = '';
const callBackName = getUrlVar(clientReq.url, 'callback') || 'autoCallBackNamePassCallbackParam';
res
.on('data', chunk => {
body += chunk;
})
.on('end', () => {
body = callBackName + '(' + body + ');';
res.headers['content-type'] = 'text/javascript; charset=utf-8';
res.headers['content-length'] = body.length;
clientRes.writeHead(res.statusCode, res.headers);
clientRes.end(body);
});
log(`${chalk.blue('serve')} (${chalk.gray(res.headers['content-type'])}) ${clientReq.url}`);
log(querystringParse(urlParse(clientReq.url).query));
log(chalk.gray(line));
});
clientReq.pipe(proxy, { end: true });
}
http.createServer(onRequest).listen(serverPort);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment