Skip to content

Instantly share code, notes, and snippets.

@cdjones32
Forked from hareeqi/change_swagger_host.js
Last active June 7, 2018 22:58
Show Gist options
  • Save cdjones32/251afd18b869578f9ea6dcaeb6526ff0 to your computer and use it in GitHub Desktop.
Save cdjones32/251afd18b869578f9ea6dcaeb6526ff0 to your computer and use it in GitHub Desktop.
dynamic host for swagger ui 3.x
// not the most elgant way but it works
// Modified to poll until the spec has loaded and then update to the current URL.
// Useful for microservices where you deploy the swagger-ui as part of the bundle and
// the Scheme/Hostname/Port are not know at runtime (for example, because they are being hosted by
// Docker, Kubernetes etc...)
function changeSwagger() {
// Try to get the Spec
var newspec = ui.spec().toJSON().resolved;
// If the spec has not been loaded yet, delay and try again
if (newspec == null || newspec.host == null) {
setTimeout(function () { changeSwagger(); }, 100);
return;
}
// We want the spec reflect our current server protocol/location/port
var scheme = location.protocol;
var host = location.hostname + (location.port ? ':' + location.port : '');
newspec.scheme = [scheme] || newspec.scheme;
newspec.host = host || newspec.host;
// If you need to change your path, do so here
// newspec.basePath = newspec.basePath;
ui.getStore().dispatch({type: 'set_scheme', payload: {scheme: newspec.scheme[0]}})
ui.getStore().dispatch({type: 'spec_update_resolved', payload: newspec})
}
changeSwagger();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment