Created
October 20, 2017 21:56
-
-
Save iadknet/7a908e9d7cd254cb7025a9d995ccaada to your computer and use it in GitHub Desktop.
swagger-proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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