Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active March 14, 2020 11:17
Show Gist options
  • Save syuji-higa/db25238a70612b493edd0e23dcd63330 to your computer and use it in GitHub Desktop.
Save syuji-higa/db25238a70612b493edd0e23dcd63330 to your computer and use it in GitHub Desktop.
Node.js - proxy server for Swagger Hub
const Koa = require('koa')
const cors = require('@koa/cors')
const axiosBase = require('axios')
const axios = axiosBase.create({
baseURL: 'https://virtserver.swaggerhub.com/[USER_ID]/[PROJECT_NAME]/1.0.0',
https: true,
headers: {
Authorization: 'API_TOKEN'
},
responseType: 'json'
})
const app = new Koa()
app
.use(cors())
.use(async (ctx, next) => {
let isAccess = true
const { method, url } = ctx.request
const res = await axios({ method, url }).catch((err) => {
if (err.response) {
const { status, data } = err.response
// API error
if (typeof data === 'object') {
ctx.status = status
ctx.body = data
console.log(data);
}
// Server error
else {
isAccess = false
console.log(err.message);
}
}
})
// Success
if (res) {
const { status, data } = res
ctx.status = status
ctx.body = data
console.log(data);
}
if(isAccess) {
await next()
}
})
const server = app.listen('8000', '0.0.0.0', () => {
const host = server.address().address
const port = server.address().port
console.log('listening at http://%s:%s', host, port)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment