Skip to content

Instantly share code, notes, and snippets.

@iadknet
Created October 20, 2017 21:56
Show Gist options
  • Save iadknet/7a908e9d7cd254cb7025a9d995ccaada to your computer and use it in GitHub Desktop.
Save iadknet/7a908e9d7cd254cb7025a9d995ccaada to your computer and use it in GitHub Desktop.
swagger-proxy
const express = require('express');
const bodyParser = require('body-parser');
const validator = require('swagger-express-validator');
const YAML = require('yamljs');
const expand = require('expand-swagger-refs').expand;
const rp = require('request-promise');
const argv = require('minimist')(process.argv.slice(2));
const HttpStatus = require('http-status-codes');
const swaggerPath = argv._[0];
const proxyURL = argv._[1];
const proxyHost = proxyURL.match(/^http[s]?:\/\/([^/]+)/)[1];
const schema = expand(YAML.load(swaggerPath));
const opts = {
schema,
validateRequest: true,
validateResponse: true,
};
const server = express()
.use(bodyParser.json())
.use(validator(opts))
.all('*', (req, res) => {
req.headers.host = proxyHost;
delete req.headers['content-length'];
const options = {
method: req.method,
uri: proxyURL + req.originalUrl,
headers: req.headers,
simple: false,
resolveWithFullResponse: true,
json: true,
};
if (Object.keys(req.body).length !== 0) {
options.body = req.body;
}
rp(options).then((response) => {
res.status(response.statusCode);
res.json(response.body);
}).catch((reason) => {
res.status(reason.statusCode);
res.json(reason.body);
});
})
.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
res.status(HttpStatus.INTERNAL_SERVER_ERROR);
res.json(err);
});
server.listen(8013, "0.0.0.0");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment