swagger-api / swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
https://swagger.io
Apache License 2.0
26.58k stars 8.96k forks source link

passing config to swagger-ui-dist to be able to set swagger URL #9237

Open Alino opened 1 year ago

Alino commented 1 year ago

How do I pass config to swagger-ui-dist?

I just need to do something like

import swaggerUI from 'swagger-ui-dist';
const swaggerUI.updateConfig({url: MY_CUSTOM_URL_TO_SWAGGER_FILE});
const swaggerUiAssetPath = swaggerUI.getAbsoluteFSPath();

ofc updateConfig method is something I made up as a pseudo code for demonstration of what I want to do.

I have seen some solution in issue https://github.com/swagger-api/swagger-ui/issues/9163 with adding a custom html initialiser. But honestly it's ugly solution and adds complexity with handling of serving this html file, and taking care of its dependencies. In my opinion kind of goes against the original idea of swagger-ui-dist. There must be a better way.

Alino commented 1 year ago

ok I have digged deeper and found some workaround which I better understood and accepted. https://github.com/swagger-api/swagger-ui/issues/5710

here is what I ended up doing

import express from 'express';
import swaggerUI from 'swagger-ui-dist';
import path from 'path';
import fs from 'fs';

export function initEndpointsDocs(app: express.Application) {
    const ENDPOINT = '/docs';
    const SWAGGER_FILE_NAME = 'swaggerFile.yaml';
    const SWAGGER_FILE_PATH = path.join(__dirname, '..', 'swagger', SWAGGER_FILE_NAME);
    const swaggerUiAssetPath = swaggerUI.getAbsoluteFSPath();

    // A workaround for swagger-ui-dist not being able to set custom swagger URL
    const indexContent = fs
        .readFileSync(path.join(swaggerUiAssetPath, 'swagger-initializer.js'))
        .toString()
        .replace('https://petstore.swagger.io/v2/swagger.json', `/${SWAGGER_FILE_NAME}`);
    app.get(`${ENDPOINT}/swagger-initializer.js`, (req, res) => res.send(indexContent));

    // Serve the swagger-ui assets
    app.use(ENDPOINT, express.static(swaggerUiAssetPath));

    // Serve the swagger file
    app.get(`/${SWAGGER_FILE_NAME}`, (req, res) => {
        res.sendFile(SWAGGER_FILE_PATH);
    });
}