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

serve swagger-ui through the swagger-ui-dist; v2 #39

Merged
merged 1 commit into from
Mar 28, 2018
Merged
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: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,5 @@ yarn.lock

package-lock.json

static

53 changes: 53 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency files and directories
node_modules
jspm_packages
yarn.lock

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# mac files
.DS_Store

# vim swap files
*.swp

package-lock.json

# project specific
*.tgz
tap-snapshots
test
.travis.yml
var
Copy link
Member

Choose a reason for hiding this comment

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

Can you remove this file?

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.

yes, I can, but, I wanted static to be ignored by git while be included in the npm. I see it's only possible with adding .npmignore.

plus I think that it's not really needed to include tests and other stuff into the package itself.

what do you think?

Copy link
Member

Choose a reason for hiding this comment

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

Oh right. Ok.

3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ node_js:
- "6"
- "4"

before_script:
- npm run prepare:swagger-ui

notifications:
email:
on_success: never
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,16 @@ Sometimes you may need to hide a certain route from the documentation, just pass
### Security
Global security definitions and route level security provide documentation only. It does not implement authentication nor route security for you. Once your authentication is implemented, along with your defined security, users will be able to successfully authenticate and interact with your API using the user interfaces of the documentation.

<a name="development"></a>
### Development
In order to start development run:
```
npm i
npm run prepare:swagger-ui
```

So that [swagger-ui](https://github.com/swagger-api/swagger-ui) static folder will be generated for you.

<a name="anknowledgements"></a>
## Acknowledgements

Expand Down
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
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"description": "Generate Swagger files automatically for Fastify.",
"main": "index.js",
"scripts": {
"test": "standard && tap test/*.js"
"prepare:swagger-ui": "node prepare-swagger-ui",
"test": "standard && tap test/*.js",
"prepublish": "npm run prepare:swagger-ui"
},
"repository": {
"type": "git",
Expand All @@ -22,12 +24,15 @@
"homepage": "https://github.com/fastify/fastify-swagger#readme",
"devDependencies": {
"fastify": "^1.1.1",
"fs-extra": "^5.0.0",
"standard": "^11.0.0",
"swagger-parser": "^4.0.2",
"tap": "^11.1.0"
"tap": "^11.1.0",
"swagger-ui-dist": "3.13.0"
},
"dependencies": {
"fastify-plugin": "^0.2.2",
"fastify-static": "^0.8.0",
"js-yaml": "^3.10.0"
},
"standard": {
Expand Down
39 changes: 39 additions & 0 deletions prepare-swagger-ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const fs = require('fs')
const fse = require('fs-extra')
const swaggerUiAssetPath = require('swagger-ui-dist').getAbsoluteFSPath()
const resolve = require('path').resolve

fse.emptyDirSync(resolve('./static'))

// since the original swagger-ui-dist folder contains non UI files
const filesToCopy = ['favicon-16x16.png',
'favicon-32x32.png',
'index.html',
'oauth2-redirect.html',
'swagger-ui-bundle.js',
'swagger-ui-bundle.js.map',
'swagger-ui-standalone-preset.js',
'swagger-ui-standalone-preset.js.map',
'swagger-ui.css',
'swagger-ui.css.map',
'swagger-ui.js',
'swagger-ui.js.map']
filesToCopy.forEach(filename => {
fse.copySync(`${swaggerUiAssetPath}/${filename}`, resolve(`./static/${filename}`))
})

const newIndex = fs.readFileSync(resolve('./static/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'),`
)

fse.writeFileSync(resolve('./static/index.html'), newIndex)
38 changes: 5 additions & 33 deletions routes.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,8 @@
'use strict'

const fp = require('fastify-plugin')
const readFileSync = require('fs').readFileSync
const resolve = require('path').resolve

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'}
}
Object.keys(files).forEach(filename => {
files[filename].contents = readFileSync(resolve(__dirname, 'static', filename), 'utf8')
})

function fastifySwagger (fastify, opts, next) {
fastify.route({
url: '/documentation/json',
Expand All @@ -43,28 +28,15 @@ 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/')
Copy link
Member

Choose a reason for hiding this comment

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

Why the dot in './documentation/'?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

so my case was the next, I serve my service under the reverse-proxy, like:
/service points to the service itself, let's say localhost:3000.

With the previous version, when I was visiting /service/documentation it was redirecting me to the /documentation/. With the current version it works fine.

Here how I've checked it:

'use strict'

const fastify = require('fastify')()
const proxy = require('fastify-http-proxy')

fastify.register(require('../index'), {
  mode: 'static',
  specification: {
    path: './examples/example-static-specification.yaml'
  },
  exposeRoute: true
})

fastify.register(proxy, {
  upstream: 'http://localhost:3000/',
  prefix: '/upstream/' // optional
})

fastify.listen(3000, err => {
  if (err) throw err
  console.log('listening')
})

(put to the script into examples, install fastify-http-proxy, open http://localhost:3000/upstream/documentation)

Copy link
Member

Choose a reason for hiding this comment

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

I think this is ok.

})

fastify.route({
url: '/documentation/:file',
method: 'GET',
schema: { hide: true },
handler: sendStaticFiles
// serve swagger-ui with the help of fastify-static
fastify.register(require('fastify-static'), {
root: resolve('./static'),
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'))
}
}

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.

Loading