Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

server swagger-ui using the swagger-ui-dist module #37

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/dynamic.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const fastify = require('fastify')()

fastify.register(require('./index'), {
fastify.register(require('../index'), {
swagger: {
info: {
title: 'Test swagger',
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
},
"dependencies": {
"fastify-plugin": "^0.2.2",
"js-yaml": "^3.10.0"
"fastify-static": "^0.8.0",
"js-yaml": "^3.10.0",
"swagger-ui-dist": "3.13.0"
},
"standard": {
"ignore": [
Expand Down
58 changes: 30 additions & 28 deletions routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,24 @@

const fp = require('fastify-plugin')
const readFileSync = require('fs').readFileSync
const resolve = require('path').resolve
const swaggerUiAssetPath = require('swagger-ui-dist').getAbsoluteFSPath()

const files = {
'index.html': {type: 'text/html'},
'oauth2-redirect.html': {type: 'text/html'},
'swagger-ui.css': {type: 'text/css'},
'swagger-ui.css.map': {type: 'application/json'},
'swagger-ui-bundle.js': {type: 'application/javascript'},
'swagger-ui-bundle.js.map': {type: 'application/json'},
'swagger-ui-standalone-preset.js': {type: 'application/javascript'},
'swagger-ui-standalone-preset.js.map': {type: 'application/json'}
// prepare index file, so it corresponds our needs
index: readFileSync(`${swaggerUiAssetPath}/index.html`, 'utf8')
.replace('window.ui = ui', `window.ui = ui

function resolveUrl (url) {
const anchor = document.createElement('a')
anchor.href = url
return anchor.href
}`)
.replace(
/url: "(.*)",/,
`url: resolveUrl('./json'),
oauth2RedirectUrl: resolveUrl('./oauth2-redirect.html'),`
)
}
Object.keys(files).forEach(filename => {
files[filename].contents = readFileSync(resolve(__dirname, 'static', filename), 'utf8')
})

function fastifySwagger (fastify, opts, next) {
fastify.route({
Expand All @@ -43,27 +46,26 @@ function fastifySwagger (fastify, opts, next) {
url: '/documentation',
method: 'GET',
schema: { hide: true },
handler: (request, reply) => reply.redirect(request.raw.url + '/')
handler: (request, reply) => reply.redirect('./documentation/')
})

fastify.route({
url: '/documentation/:file',
method: 'GET',
schema: { hide: true },
handler: sendStaticFiles
// server swagger-ui with the help of fastify-static
fastify.register(require('fastify-static'), {
root: swaggerUiAssetPath,
prefix: `/documentation/`
})

function sendStaticFiles (req, reply) {
if (!req.params.file) {
const file = files['index.html']
reply.type(file.type).send(file.contents)
} else if (files.hasOwnProperty(req.params.file)) {
const file = files[req.params.file]
reply.type(file.type).send(file.contents)
} else {
return reply.code(404).send(new Error('Not found'))
// hijak swagger index.html response
fastify.addHook('onSend', (request, reply, payload, next) => {
if (
request.raw.originalUrl === `/documentation/` ||
request.raw.originalUrl === `/documentation/index.html`
) {
reply.header('Content-Type', 'text/html; charset=UTF-8')
payload = files.index
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should not be needed, maybe fastify-static has a bug. Why do you need it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is needed since I do not change the file from the original and content of swagger-ui-dist remains the same. But I hijack the request to the root or index.html and send our custom file instead of the default index.html.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think these prefixes are correct. I can mount this plugin with a given /swagger and it will add the ui as /swagger/documentation/.

A better approach would be to either have a post-install script or a prepublish  script where we do these changes and replacements. A prepublish might be better, because we can't guarantee that regexps are stable across versions. Why do we need those changes anyway?

Copy link
Contributor Author

@PavelPolyakov PavelPolyakov Mar 25, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes needed because by default it index.html of the swagger ui leads to the pet store.
https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html

I can mount this plugin with a given /swagger and it will add the ui as /swagger/documentation/.

how would you do that? I think prefix option is not supported.

I've tried this together with example/dynamic.js:

fastify.register(require('../index'), {
  swagger: {
    info: {
      title: 'Test swagger',
      description: 'testing the fastify swagger api',
      version: '0.1.0'
    },
    host: 'localhost',
    schemes: ['http'],
    consumes: ['application/json'],
    produces: ['application/json']
  },
  exposeRoute: true,
  prefix: '/swagger'
})

the documentation appeared on localhost:3000/documentation still.

a prepublish script where we do these changes and replacements.

you mean on prepublish we copy everything into our static folder and then serve it instead of the original swagger-ui-dist?

A prepublish might be better, because we can't guarantee that regexps are stable across versions.

Yes, the original html can be changed, but since the version is fixed, I think it's safe to rely on the regex.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the new variant #39

}
}
next(null, payload)
})

next()
}
Expand Down
99 changes: 0 additions & 99 deletions static/index.html

This file was deleted.

60 changes: 0 additions & 60 deletions static/oauth2-redirect.html

This file was deleted.

125 changes: 0 additions & 125 deletions static/swagger-ui-bundle.js

This file was deleted.

1 change: 0 additions & 1 deletion static/swagger-ui-bundle.js.map

This file was deleted.

13 changes: 0 additions & 13 deletions static/swagger-ui-standalone-preset.js

This file was deleted.

1 change: 0 additions & 1 deletion static/swagger-ui-standalone-preset.js.map

This file was deleted.

2 changes: 0 additions & 2 deletions static/swagger-ui.css

This file was deleted.

1 change: 0 additions & 1 deletion static/swagger-ui.css.map

This file was deleted.

8 changes: 0 additions & 8 deletions static/swagger-ui.js

This file was deleted.

1 change: 0 additions & 1 deletion static/swagger-ui.js.map

This file was deleted.

57 changes: 8 additions & 49 deletions test/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ const Fastify = require('fastify')
const Swagger = require('swagger-parser')
const yaml = require('js-yaml')
const fastifySwagger = require('../index')
const readFileSync = require('fs').readFileSync
const resolve = require('path').resolve

const swaggerInfo = {
swagger: {
Expand Down Expand Up @@ -165,7 +163,7 @@ test('fastify.swagger should return a valid swagger yaml', t => {
})

test('/documenatation should redirect to /documentation/', t => {
t.plan(5)
t.plan(4)
const fastify = Fastify()

fastify.register(fastifySwagger, swaggerInfo)
Expand All @@ -183,17 +181,13 @@ test('/documenatation should redirect to /documentation/', t => {
}, (err, res) => {
t.error(err)
t.strictEqual(res.statusCode, 302)
t.strictEqual(res.headers['location'], '/documentation/')
t.strictEqual(res.headers['location'], './documentation/')
t.is(typeof res.payload, 'string')
t.strictEqual(
'',
res.payload
)
})
})

test('/documenatation/:file should send back the correct file', t => {
t.plan(20)
t.plan(15)
const fastify = Fastify()

fastify.register(fastifySwagger, swaggerInfo)
Expand All @@ -211,14 +205,7 @@ test('/documenatation/:file should send back the correct file', t => {
}, (err, res) => {
t.error(err)
t.is(typeof res.payload, 'string')
t.is(res.headers['content-type'], 'text/html')
t.strictEqual(
readFileSync(
resolve(__dirname, '..', 'static', 'index.html'),
'utf8'
),
res.payload
)
t.is(res.headers['content-type'], 'text/html; charset=UTF-8')
})

fastify.inject({
Expand All @@ -227,14 +214,7 @@ test('/documenatation/:file should send back the correct file', t => {
}, (err, res) => {
t.error(err)
t.is(typeof res.payload, 'string')
t.is(res.headers['content-type'], 'text/html')
t.strictEqual(
readFileSync(
resolve(__dirname, '..', 'static', 'oauth2-redirect.html'),
'utf8'
),
res.payload
)
t.is(res.headers['content-type'], 'text/html; charset=UTF-8')
})

fastify.inject({
Expand All @@ -243,14 +223,7 @@ test('/documenatation/:file should send back the correct file', t => {
}, (err, res) => {
t.error(err)
t.is(typeof res.payload, 'string')
t.is(res.headers['content-type'], 'text/css')
t.strictEqual(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui.css'),
'utf8'
),
res.payload
)
t.is(res.headers['content-type'], 'text/css; charset=UTF-8')
})

fastify.inject({
Expand All @@ -259,14 +232,7 @@ test('/documenatation/:file should send back the correct file', t => {
}, (err, res) => {
t.error(err)
t.is(typeof res.payload, 'string')
t.is(res.headers['content-type'], 'application/javascript')
t.strictEqual(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui-bundle.js'),
'utf8'
),
res.payload
)
t.is(res.headers['content-type'], 'application/javascript; charset=UTF-8')
})

fastify.inject({
Expand All @@ -275,14 +241,7 @@ test('/documenatation/:file should send back the correct file', t => {
}, (err, res) => {
t.error(err)
t.is(typeof res.payload, 'string')
t.is(res.headers['content-type'], 'application/javascript')
t.strictEqual(
readFileSync(
resolve(__dirname, '..', 'static', 'swagger-ui-standalone-preset.js'),
'utf8'
),
res.payload
)
t.is(res.headers['content-type'], 'application/javascript; charset=UTF-8')
})
})

Expand Down