| 5 | const path = require('path') |
| 6 | |
| 7 | export default function setupSwaggerUI(app) { |
| 8 | if (API_CONFIG.documentation) { |
| 9 | return |
| 10 | } |
| 11 | |
| 12 | const serveSwaggerDef = function serveSwaggerDef(req, res) { |
| 13 | res.sendFile(path.resolve(`${__dirname}/../documentation/openapi.json`)) |
| 14 | } |
| 15 | app.get('/documentation-config', serveSwaggerDef) |
| 16 | |
| 17 | const swaggerUiAssetPath = require('swagger-ui-dist').getAbsoluteFSPath() |
| 18 | const swaggerFiles = express.static(swaggerUiAssetPath) |
| 19 | |
| 20 | const urlRegex = /url: "[^"]*",/ |
| 21 | |
| 22 | const patchIndex = function patchIndex(req, res) { |
| 23 | const indexContent = fs |
| 24 | .readFileSync(`${swaggerUiAssetPath}/index.html`) |
| 25 | .toString() |
| 26 | .replace(urlRegex, 'url: "../documentation-config",') |
| 27 | res.send(indexContent) |
| 28 | } |
| 29 | |
| 30 | app.get('/documentation', (req, res) => { |
| 31 | let targetUrl = req.originalUrl |
| 32 | if (!targetUrl.endsWith('/')) { |
| 33 | targetUrl += '/' |
| 34 | } |
| 35 | targetUrl += 'index.html' |
| 36 | res.redirect(targetUrl) |
| 37 | }) |
| 38 | app.get('/documentation/index.html', patchIndex) |
| 39 | |
| 40 | app.use('/documentation', swaggerFiles) |
| 41 | } |