Giter Club home page Giter Club logo

hapi-swaggered-ui's Introduction

hapi-swaggered-ui

Easy swagger-ui (v3) drop-in plugin for hapi to be used with hapi-swaggered.

Supports hapi 17.x and up For earlier versions check hapi-swaggered-ui 2.x (current default/latest npm install hapi-swaggered --save)

Build Status js-standard-style npm downloads

Install

npm install hapi-swaggered-ui@next

Configuration

  • title: string, title of swagger ui
  • path: string, optional path where the docs should be located at (e.g. '/docs', defaults to: null)
  • basePath: string, optional url base path (e.g. used to fix reverse proxy routes)
  • swaggerEndpoint: Override the auto-detection of hapi-swaggered with a specific URL. (not recommended in use with hapi-swaggered; optional)
  • swaggerOptions: object (according to swagger-ui)
    • operationsSorter: Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method), null (server side sorting) or a custom function (see link above).
    • docExpansion: Controls how the API listing is displayed. It can be set to 'none' (default), 'list' (shows operations for each resource), or 'full' (fully expanded: shows operations and their details).
    • validatorUrl: By default, Swagger-UI attempts to validate specs against swagger.io's online validator (disabled for localhost). You can use this parameter to set a different validator URL, for example for locally deployed validators (Validator Badge). Setting it to false will disable validation. This parameter is relevant for Swagger 2.0 specs only.
    • In addition the following options are supported: oauth2RedirectUrl, configUrl, displayOperationId, displayRequestDuration, filter, deepLinking, maxDisplayedTags, tagsSorter, parameterMacro, modelPropertyMacro - have a look at swagger-ui
  • authorization: object - can be null or false to disable authorization through swagger-ui (e.g. in case of public apis without auth)
    • scope: string, 'query' or 'header'
    • field: string, name of the field
    • valuePrefix: string, prefix fields value (e.g. with 'bearer ')
    • defaultValue: string, default value of the api-key field
    • placeholder: string, placeholder of the api-key field
  • auth: object, auth options as specified in route options (hapi docs), will be applied to all registered plugin routes
  • defaultTags: array of strings, will be passed to the specs endpoint through the query param 'tags' (hapi-swaggered feature: tag filtering)

Example

Since hapi-swaggered exposes its plugin configuration hapi-swaggered-ui should find it's swagger endpoint automatically. In case you want to use hapi-swaggered-ui without hapi-swaggered (or the auto-detection doesn't work) you can manually set the swagger endpoint by the swaggerEndpoint option. In addition the page title can be changed through the option title.

await server.register([
  require('inert'),
  require('vision'),
  {
    plugin: require('hapi-swaggered-ui'),
    options: {
      title: 'Example API',
      path: '/docs',
      authorization: { // see above
        field: 'apiKey',
        scope: 'query', // header works as well
        // valuePrefix: 'bearer '// prefix incase
        defaultValue: 'demoKey',
        placeholder: 'Enter your apiKey here'
      },
      swaggerOptions: {} // see above
    }
  }
])

May have a look at the example listed at https://github.com/z0mt3c/hapi-swaggered

hapi-swaggered-ui's People

Contributors

craigbeck avatar dcharbonnier avatar felixheck avatar greenkeeperio-bot avatar savardc avatar tatort79 avatar z0mt3c avatar zachguo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

hapi-swaggered-ui's Issues

Hapi 9.0 removes inert and vision plugins

Using hapi-swaggered-ui with hapi v9.0.3 results with an error on startup:

Error: Plugin hapi-swaggered-ui missing dependency vision in connection: http://0.0.0.0:8081

solution: install vision and inert as top level dependencies (they are already included as dependencies of hapi-swaggered-ui) and register them with your server.

install:

$ npm install --save vision inert

register:

var Inert = require("inert");
var Vision = require("vision");

server.register([
  Inert,
  Vision,
  /* register other plugins including hapi-swaggered and hapi-swaggered-ui */
], funciton (err) { /* other stuff */ })

Wrong mapping on path parameters when generating the request URL

Problem:

With such a request:

/this/{test}/is/{testABC}/a/{testABCDEF}/test/{other}/of/{otherABC}/swagger/{otherDEF}/ui

The swaggered-ui generates the right parameters in the UI.

But, when I press the Try it button, the value of the parameter test is placed on all the {test*} and other is placed on all the {other*}, in the Request URL.

Example:

I made a screenshot:
hapi-swaggered-ui-path-bug-1

The expected result should be:

http://192.168.2.51:80/this/id1/is/id2/a/id3/test/id4/of/id5/swagger/id6/ui

Quoting issues when using Joi validation on delete route

I have a validation scheme

{
  playerIds: Joi.array().items(Joi.string().guid()).required()
}

and say i send a bad message of {"playerIds": ["string"]}

That works great for POST/PUT payload/body validation and GET reply. However when using DELETE method via the hapi-swaggered parameter window. I get this.

{
  "success": false,
  "error": {
    "type": "ValidationError",
    "description": "child \"playerIds\" fails because [\"playerIds\" is required]. \"{
  "playerIds": \" is not allowed",
    "details": [
      {
        "message": "\"playerIds\" is required",
        "path": "playerIds",
        "type": "any.required",
        "context": {
          "key": "playerIds"
        }
      },
      {
        "message": "\"{
  "playerIds": \" is not allowed",
        "path": "{\n  \"playerIds\": ",
        "type": "object.allowUnknown",
        "context": {
          "key": "{\n  \"playerIds\": "
        }
      }
    ]
  }
}

Note that if I use POSTman or curl with the same json it gives the proper validation error of

{
  "success": false,
  "error": {
    "type": "ValidationError",
    "description": "child \"playerIds\" fails because [\"playerIds\" at position 0 fails because [\"0\" must be a valid GUID]]",
    "details": [
      {
        "message": "\"0\" must be a valid GUID",
        "path": "playerIds.0",
        "type": "string.guid",
        "context": {
          "value": "string",
          "key": 0
        }
      }
    ]
  }
}

It appears DELETE's param window is somehow escaping things improperly. Any thoughts?

Optional parameters being sent as encoded

I have a route defined as

{
  method: "GET",
  path: `/${model_name}/{id?}`,
  config: {
    handler: Functions.GET.bind(models[model_name]),
    description: `Get a paginated list of "${model_name}"`,
    notes: `Return a list of "${model_name}" in the database. If an ID is passed, return matching documents.`,
    tags: ["api", model_name],
    validate: {
      params: Joi.object({
        id: Joi.string().optional().description(`ID of the ${model_name} to get`)
      })
    },
    response: {
      schema: Joi.array().items(reply_joi)
        .meta({
          className: `Get ${model_name}`
        })
    }
  }
},

But the UI shows the ID without the optional flag ? and sends the request as %7Bid%7D

"Expand all" button

What you think about "Expand all" button? Would be useful when searching on page through endpoints

specifying a custom template

I am experimenting with the latest version of hapi-swaggered + hapi-swaggered-ui. So far so good. However, I would like to use my own handlebars template for the docs as well as to match the look and feel of the rest of the project. I created my own docs.hbs content and layout following templates/indexhbs, but of course, I can't figure out how to tell the plugin to use them. Is there an option setting where I can specify a different template?

Plus, (and this is not a huge setback but), I'd like to specify .html as the extension for my templates. I already use the following invocation

server.views({
        engines: {
            html: require('handlebars')
        },
        relativeTo: __dirname,
        path: './views',
        layoutPath: './views/layouts',
        partialsPath: './views/partials',
        layout: 'main',
        isCached: false
    });

Of course, I can add hbs: require('handlebars') to the engines section above, and that seems to work, but it would be simpler if all my templates could have the same extension.

Update: So I was able to do this by adding the following five settings to the plugin options

const hapiSwaggeredUiOpts = {
    
    relativeTo: __dirname,
    contentTemplate: 'docs',
    layoutTemplate: 'docs',
    templates: './views',
    layoutPath: './views/layouts',
    partialsPath: './views/partials',}

and creating my custom templates in the above specified directories. Of course, I had update lib/index.js to accommodate the above settings.

I am sure a zillion things can go wrong with what I did, but it seems to work for me without any problem.

“ie” Browser not display

Solution: /templates/index.hbs

`<script>
window.onload = function() {

if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}

target = Object(target);
for (var index = 1; index < arguments.length; index++) {
  var source = arguments[index];
  if (source != null) {
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
}
return target;

};
}

// Build a system
const ui = SwaggerUIBundle(Object.assign({
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
}, {{{swaggerOptions}}}))

var oauthOptions = {{{oauthOptions}}};
if (oauthOptions) ui.initOAuth(oauthOptions)

window.ui = ui
}
</script>`

https://github.com/zhr85210078/hapi-swaggered-ui/edit/master/templates/index.hbs

Hapi v17 support

Hapi recently released a new version (v17, see the release notes) which introduces many breaking changes. Will this plugin support the new version?

Allow customization of hapi route options

For security reasons, I would like the swagger ui to include a content security policy. To do this we can use a hapi plugin called blankie.

The following is a plugin configuration and is applied globally to all routes

{
    plugin: require("blankie"),
    options: {
      fontSrc: ["self", "fonts.gstatic.com", "data:"],
      styleSrc: ["self", "fonts.googleapis.com", "unsafe-inline"],
      scriptSrc: ["self", "unsafe-inline"],
      imgSrc: ["self", "data:"],
      generateNonces: false,
    },
  }

Rather than applying this configuration globally I would like to configure the blankie plugin at the route level so the content security policy is defined as strictly as possible

This is achievable in the hapi ecosystem by the plugins route option

{
   ...
   plugins: {
      blankie: {
        fontSrc: ["self", "fonts.gstatic.com", "data:"],
        styleSrc: ["self", "fonts.googleapis.com", "unsafe-inline"],
        scriptSrc: ["self", "unsafe-inline"],
        imgSrc: ["self", "data:"],
        generateNonces: false,
      }
   },
}

it would be ideal if the hapi-swaggered-ui plugin options exposed a mechanism to control the route options

for example

{
    plugin: require("hapi-swaggered-ui"),
    options: {
      title: "My Documentation",
      path: "/documentation",
      swaggerOptions: {
        docExpansion: "list",
      },
      routeOptions: {
        ...anyOtherValidRouteOptions
        plugins: {
          blankie: {
            fontSrc: ["self", "fonts.gstatic.com", "data:"],
            styleSrc: ["self", "fonts.googleapis.com", "unsafe-inline"],
            scriptSrc: ["self", "unsafe-inline"],
            imgSrc: ["self", "data:"],
            generateNonces: false,
          }
        },
      },
    },
  }

This would not only enable my specific use case about control route specific plugins but would also allow any other customization of the route configuration that users of this plugin may desire.

Reverse proxy support

Currently, we have a reverse proxy in front of where we are hosting hapi-swaggered that is using path namespacing for the individual apps. Because of this, there is a base path that hapi-swaggered is not aware of, so all of the routes generated produce invalid URLs since this base path is not being added on.

Could we add a basePath or similar configuration parameter to prefix all routes with when generating the resulting URLs?

This is related to z0mt3c/hapi-swaggered#39

hiding the top green swagger bar

I would like to not show the green swagger top bar

swagger

Right now I can hide that bar by using an inline stylesheet like below, but I'd rather not have this be generated and sent to the browser at all.

 .swagger-ui .topbar {
            display: none;
            visibility: hidden;
}

Update swagger-ui-dist dependency

There's a bug that's really annoying with the current version of swagger-ui that's being used by hapi-swaggered-ui:
swagger-api/swagger-ui#4107

This has been long fixed in the lib, but the version constraint here does not allow for that bugfix to spread.

I've manually updated the dependency in 4 of my projects and encountered no issues.

I'd do a PR myself, but the project lacks contributing guidelines and I'm no JS expert. I can try, though, if anybody can help me if and when I get stuck.

Cheers!

Please upgrade hapi dependency

Hello, we are using Hapi 18 and and when we use swagger on it it's giving warning for Hapi Dependency Upgrade..
Like below

inert:x.x.x is now in @hapi/insert : x.x.x

Allow `auth` as a plugin option

Something like auth option in hapi-swaggered would be nice.

auth: authentication configuration hapijs documentation (default to undefined)

I can take on this and create a PR if you like.

hapi-swaggered-ui stopped working, "views manager is not configured"

Unhandled rejection Error: Cannot render view without a views manager configured

my docs used to render, then we upgraded

i have the vision plugin required, though i did not configure it with server.views(...) i never had to before

is there a configuration that i should be using?

this does not work

      server.views({
        engines: { html: require( "handlebars" ) },
        path: __dirname + '/node_modules/hapi-swaggered-ui/templates'
      });

node : v5.0.0
npm : 3.3.6
hapi : 11.1.2
hapi-swaggered : 2.4.1
hapi-swaggered-ui : 2.1.1

Reducing security vulnerabilities

Hey, we are using your tool and our audit procedures report unfixed vulnerabilites within your project. Since I don't want to fork it, I would like to submit a PR with the fixes. Please let me know if this is an option for you.

Enable configurable routes

Hi,

When I have a non RFC-6265 compliant cookie (like one with a space in the value but not wrapped in quotes) then this /docs route will fail with the message
{"statusCode":400,"error":"Bad Request","message":"Invalid cookie value"}

Hapi provides a way to prevent this, which is setting the route with config like such

server.route({
	path: '/',
	method: 'GET',
	config: {
		state: {
			parse: false
		}
	},

So, when this plugin registers its routes, it could first merge the config object with something supplied by the user, both solving this exact scenario and perhaps others.

Error: Plugin hapi-swaggered-ui missing dependency vision

Not sure why, as I see you registering the dependency with server.dependency.....

/dev/project/node_modules/hapi/node_modules/hoek/lib/index.js:731
    throw new Error(msgs.join(' ') || 'Unknown error');
          ^
Error: Plugin hapi-swaggered-ui missing dependency vision in connection: http://local:8080
    at Object.exports.assert (/dev/project/node_modules/hapi/node_modules/hoek/lib/index.js:731:11)
    at internals.Server.initialize (/dev/project/node_modules/hapi/lib/server.js:175:22)
    at internals.Server.start (/dev/project/node_modules/hapi/lib/server.js:147:10)
    at /dev/project/app.js:17:12
    at /dev/project/node_modules/glue/lib/index.js:122:9
    at done (/dev/project/node_modules/items/lib/index.js:30:25)
    at done (/dev/project/node_modules/items/lib/index.js:30:25)
    at /dev/project/node_modules/hapi/lib/plugin.js:261:16
    at done (/dev/project/node_modules/hapi/node_modules/items/lib/index.js:30:25)
    at Object.exports.register (/dev/project/node_modules/hapi-swaggered-ui/lib/index.js:194:10)

For what its worth. I got around the issue by adding vision to my application dependencies itself.

authorization not working on 3.0.1

Using the options below, the authorization fields don't appear on the swagger page. It used to for v2.x

            {
                plugin: require("hapi-swaggered-ui"),
                options: {
                    title: "medipass",
                    path: "/docs/partner",
                    authorization: {
                        field: "x-appid",
                        scope: "header",
                        placeholder: "Enter your application ID here"
                    },
                    auth: {
                        mode: "required",
                        strategies: ["apiDocs"]
                    },
                    swaggerOptions: {
                        validatorUrl: false
                    }
                }
            }

Add missing `swagger-ui` display options

Having a look to swagger-ui configuration options, there are quite useful options not handled in the happi-swaggered-ui.

Especially these 3 properties.

Parameter Name Description
defaultModelsExpandDepth Number=1. The default expansion depth for models (set to -1 completely hide the models).
defaultModelExpandDepth Number=1. The default expansion depth for the model on the model-example section.
defaultModelRendering String=["example"*, "model"]. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)

Support defaultTags

I'm curious why you removed the defaultTags option in 33f4001 ? That configuration setting is referenced in

} if (settings.defaultTags) {
. I was hoping to use this feature to restrict the generated UI to just "public" routes.

Is there a different configuration option I should be using instead of defaultTags?

Nested array breaks UI

I am trying out swaggered with swaggered UI. And I have a nested array because I want to input Geo JSON data into a Geo Shape in Elasticsearch. See configuration http://pastebin.com/NfDJaUUu.

The code yields an error when loading /docs. The result is that the UI displays a message, fetching resource list: http://localhost:5000/swagger. Which is the result of a script error when parsing the data from /swagger.

An error is thrown from /lib/types/model.jsat line 223. model.js:223Uncaught TypeError: Cannot read property '$ref' of undefined. I do not know if this is because the returned data is invalid or if it is the UI which is at fault.

I am running:
Node 0.10.38
hapi-swaggered 2.0.2
hapi-swaggered-ui 1.3.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.