Git Product home page Git Product logo

feathers-swagger's Introduction

feathers-swagger

CI Download Status

Add OpenAPI documentation to your Feathers services and optionally show them in the Swagger UI.

You can also add custom methods to feathers services that will be available as rest routes but not via the feathers client.

Checkout the Documentation for further information.

Changelog

License

Copyright (c) 2016 - 2023

Licensed under the MIT license.

feathers-swagger's People

Contributors

alexisabril avatar andys8 avatar ashotn avatar bitflower avatar bravo-kernel avatar c10h22 avatar corymsmith avatar cpsubrian avatar daffl avatar deskoh avatar ekryski avatar espadav8 avatar glavin001 avatar greenkeeper[bot] avatar greenkeeperio-bot avatar ivanmarjanovic avatar jamesjnadeau avatar jraut avatar kristianmandrup avatar lpreterite avatar mairu avatar paul42 avatar psi-4ward avatar sarkistlt avatar sinedied avatar snyk-bot avatar superbarne avatar thiemok avatar xfurymaxhd 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar

feathers-swagger's Issues

[How to] add documentation for the /auth/xxx endpoints

I had to figure out how to do this. Here is what I did:

I did not want the documentation for the token endpoints thus I removed them from the object:
services/authentication/index.js

  ...
  app.configure(authentication(config));
  //Removing endpoints from the documentation
  delete app.docs.paths['/auth/token'];
  delete app.docs.paths['/auth/token/{id}'];

Then I merged a definition that I keep in a separate file (here is an explanation or check the project I am working on)

app.docs.paths['/auth/token'].post = Object.assign({}, app.docs.paths['/auth/token'].post, def.post);

Using $ref

Is it possible to use $ref with URI instead of definitions?

Use default swagger-ui?

It would be nice to also allow using the default index.html provided with swagger-ui instead of having to always provide our own, what do you think?

A property ui: true could be used, or a special value for the uiIndex property like `uiIndex: 'default'.

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Update npm version

The npm version is still 0.2.0, so running npm install feathers-swagger yields an outdated version that doesn't really work with the current swagger ui.

Supported in Feathers 2?

Since this is the only info I can find regarding Feathers 2 support for this package, I'm guessing it hasn't been updated for F2.

Any additional information available regarding future plans for continuing this, or some specifics on what would need to get updated? I have to start generating Swagger docs more or less immediately, and deciding what path of least resistance is.

Space in name leads to non RFC3986-compliant percent-encoded URI

Issue

Lists contain a space in their name.
Using editor this is not allowed.

Solution

space could be replaced with dash (-) or another character.

Error

Semantic error at paths./campaigns.get.responses.200.schema.$ref
$ref values must be RFC3986-compliant percent-encoded URIs

Code

Name with space used for lists:

'$ref': '#/definitions/' + `${tag} list`

Generated here:

rootDoc.definitions[`${tag} list`] = {

Swagger & Express

Thanks for the library. I'm having some trouble getting this working when using Express as my transport provider:

Steps to reproduce

Requires feathers, express, and feathers-swagger.

  • Tell us what broke. The more detailed the better.
  • If you can, please create a simple example that reproduces the issue and link to a gist, jsbin, repo, etc.

https://gist.github.com/danielneri/bee112e16ef907a47c758756b112c58e

Expected behavior

Docs should generate.

Actual behavior

/docs renders a 404 error.

System configuration

Tell us about the applicable parts of your setup.

Module versions (especially the part that's not working):

[email protected] /Users/...
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

NodeJS version:

v8.11.2

Operating System:

macOS High Sierra

Browser Version:

React Native Version:

Module Loader:

Definition for prefixed routes

All my services are versioned and available under the /api/{version}/ prefix.

I'm trying to create definition for my services, but they all end up in the api swagger group, is there a way to prevent this?

discussion: introspect services for pre and post hooks, and other routes

  1. Should we automate documentation of pre and post hooks? All hooks, or just often used hooks

  2. Should we introspect services (or even the underlying app) for routes not defined in the service itself?

# For example
app.use('/users', service);
app.service('users')
   .hooks(hooks);
app.post('/users/password', handlePasswordReset);

@daffl - https://feathersjs.slack.com/archives/C52QSFK0A/p1507333034000102

I think the conversation is worth having. Maybe we decide that automation/automated introspection is not the answer, and maybe just more robust documentation on the best way to use swagger to document hook like functionality.

Thanks for all of the great work!!

Work with Swagger Editor & YAMLconfig files

I wish this project were more like swagger-node where you can edit the swagger YAML in the editor then use feathers-cli to generate the services based on the YAML.

The editor is a great feature of the Swagger toolset and you really should write the specification for the API before you code it.

So, instead of manually creating the doc property on each of the service objects, one would be created automatically based on the YAML specification created in the editor. The feather-cli would then be able to read the specification and then be able to tell with services needed to be created/modified/removed when the YAML file was changed in the editor.

The feathers-cli would also generate test suites based on the YAML specification to make sure the services were implemented properly according to the specifications.

exclude

is it possible to exclude certain services?

Can't read from file /docs

Hi,

I setup swagger ui using the following configuration:

app.configure(swagger({
    docsPath: "/docs",
    uiIndex: true,
    info: {
      title: "Title",
      description: "Description"
    }
  }));

But I get the following error on the bottom of the page:

{
  "schemaValidationMessages": [
    {
      "level": "error",
      "message": "Can't read from file /docs"
    }
  ]
}

Add support for service groups

Steps to reproduce

I'm building an API with a lot of exposed services that belong to different groups.
For example, I have a group prospecting, with 8 different services inside it. What I want to achieve is URI structure like "prospects/persons/{id}", "prospects/companies/{id}" and so on.

To archive that, I'm defining my services like so:

  app.use('/prospects/persons', Object.assign(memory(), {docs}));

It works: API endpoints are available and SwaggerUI shows all endpoints.
But there are some serious problems.

Expected behaviour

What I want to do is to define docs for every of my sub-services and see them in Swagger. Also, ideally, I would like them to be displayed as different groups in SwaggerUI.

Actual behaviour

When I do so, they all appear under same tag "prospects" - this means that I can't set definitions for them (every definition is replacing the previous one) and can't group them by actual service name.

The problem is here because of automatic tags generation. It would be great to have an ability to:

  • set custom tags for service;
  • or at least support nested routes during generation.

System configuration

Module versions:

Should redirect from /docs to /docs/

Steps to reproduce

spin up a server and go to /docs without the trailing slash

Expected behavior

It should show the UI

Actual behavior

it doesn't

Is there a version that works with OAS 2.0?

Just wondering...is there a version of this that supports Swagger 2? I need to make a Python SDK using bravado(a python codegen tool based on OAS 2.0) and they don't plan to add 3.0 support.

bug: resourceId not set as literal

when a post/put/patch is done, the resourceId is not expanded, as the url contains dynamic ids, like {_id}, instead of always {resourceId}

I have fixed this by replacing line lib/index.js:105 with:

    var withIdKey = '/' + path + '/{resourceId}';

Sorry, but I don't have the time right now to do a proper pull request.

Code generated using feathers cli, unable to use swagger with authentication

## Steps to reproduce

  • Tell us what broke. The more detailed the better.

I have tried to troubleshoot this as per issue #36 . But so far never got it working.

I have feathers-swagger working up to displaying Swagger UI and using it to execute get and post for services that does not require authentication.

However after enabling authentication, I got error as per bellow screenshot:

error
The reply at the end of Issue #35 might have similar problem.

Bellow code is in messages.services.js

const messages = createService(options);
  messages.docs = {
    description: "A service to send and receive chat messages",
    definitions: {
      messages: {
        type: "object",
        required: ["text"],
        properties: {
          text: {
            type: "string",
            description: "The message text"
          },
          userId: {
            type: "string",
            description: "The id of the user that send the message"
          }
        }
      }
    }
  };

  app.use("/messages", messages);

And this one in app.js

//Swagger
app.configure(
  swagger({
    docsPath: "/docs",
    uiIndex: true,
    info: {
      title: "Feathers Chat Backend",
      description: "Feathers chat backend!"
    },
   securityDefinitions: {
      bearer: {
        type: "apiKey",
        name: "authorization",
        in: "header"
      }
    },
    security: [
      {
        bearer: []
      }
    ]
  })
);
  • If you can, please create a simple example that reproduces the issue and link to a gist, jsbin, repo, etc.

I have created example to demonstrate this issue using feathers-chat repo

Github - feathers-chat-swagger

Expected behavior

As per #36 I did see bellow screen. So something work. But expected get and post for authenticated service to work.

image

Authorization input

I realise that this might not be specifically related to feathers-swagger. But we should be able to figure this out together, and add it to this repos installation instructions

Expected behavior

Input field in header that allows the user to add a token to be included with every request.

Actual behavior

No token gets added to requests

What I have done

  • Installed current feathers-cli
  • generated new app
  • added featers-swagger as stated in readme
    customized docs.html to add a input#input_apiKey field to the header

app.js:

const swagger = require('feathers-swagger');
...
app.use(compress())
  .options('*', cors(corsOptions))
  .use(cors(corsOptions))
  .use(favicon( path.join(app.get('public'), 'favicon.ico') ))
  .use('/', serveStatic( app.get('public') ))
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(hooks())
  .configure(swagger({
    docsPath: '/docs',
    uiIndex: path.join(__dirname, '../docs/docs.html'),
    info: {
      title: 'Feathers app API server',
      description: 'This server allows... '
    }
  }))
  .configure(rest())
  .configure(socketio())
  .configure(services)
  .configure(middleware);
...

services/user/index.js:

module.exports = function() {
  const app = this;

  const options = {
    Model: user,
    paginate: {
      default: 5,
      max: 25
    }
  };

  const Service = service(options);

  Service.docs = {
    description: 'A service to manage users',
    definitions: {
      users: {
        "type": "object",
        "required": [
          "email",
          "password"
        ],
        "properties": {
          "email": {
            "type": "string",
            "description": "User email"
          },
          "password": {
            "type": "string",
            "description": "User Password"
          },
          "createdAt": {
            "type": "string",
            "description": "object creation date"
          },
          "updatedAt": {
            "type": "string",
            "description": "Last time the object was updated"
          }
        }
      }
    }
  };

  // Initialize our service with any options it requires
  app.use('/users', Service);

  // Get our initialize service to that we can bind hooks
  const userService = app.service('/users');

  // Set up our before hooks
  userService.before(hooks.before);

  // Set up our after hooks
  userService.after(hooks.after);
};

Oher notes

window.ApiKeyAuthorization is deprecated. we should use SwaggerClient.ApiKeyAuthorizationinstead
window.authorizations is deprecated. We should use SwaggerUi.api.clientAuthorizations.add()instead.

Did it working with last swagger 3.0

this thread is not a bug but i want to share my work to make it working with version 3.0
installed swagger-ui v2 (then overrided the folder dist of the last v3

Change to do in feathers-swagger/lib/index.js:

var rootDoc = Object.assign({
...
swagger: '3.0',
...
ignore: {
tags: []
}
}, config || {});

in each parameters change
{...
name: 'resourceId',
type: 'integer'
...}
to
{...
name: '_id',
type: 'string'
....}

then
then i overrided node_modules/feathers-swagger/dist/ from the last dist v3 of swagger
change node_modules/feathers-swagger/dist/

in configure:
foce uiIndex to be in dist of your modules
var modulesRootPath = require.resolve('swagger-ui');
modulesRootPath = modulesRootPath.substr(0, modulesRootPath.lastIndexOf('node_modules'));
.configure(swagger({
docsPath: '/docs',
uiIndex: path.join(modulesRootPath, 'node_modules/swagger-ui/dist/index.html'),
}))

I tested it's working well with the mods (i tested in https ) .

docs ignored when path already exists

Version: 0.3.1

// Service definiton

module.exports = function(){
  const app = this;
  const db = new NeDB(...);
  // ...
  app.use('/projects/:projectId/sync', projectsSyncService);
  
  const docs = { description: 'My Project Service' }
  app.use('/projects', Object.assign(service(options), { docs }) );

The first app.use spawns the projects tag in the spec and the docs definition from app.use('/projects' gets ignored by
https://github.com/feathersjs/feathers-swagger/blob/master/src/index.js#L220

The workaround is add the docs to the very first use but it's way confusing and the sub-service should hold its own docs. Probably we should use the group-defs only for first-level paths or merge the defs?

Resolve Errors displayed in Swagger UI

After adding the Swagger UI I got a lot of errors:

Resolver error at paths./users.get.responses.200.schema.$ref
Could not resolve reference because of: Could not resolve pointer: /definitions/users list does not exist in document
Resolver error at paths./users.post.parameters.0.schema.$ref
Could not resolve reference because of: Could not resolve pointer: /definitions/users does not exist in document

I am using:

"@feathersjs/feathers": "^3.0.5",
"feathers-swagger": "^0.6.0",

How to fix this?

path/{template} per service -> per method

Expected behavior

By default the path template uses idas path parameter. We can set an id with a value that overrides the default path parameter. This is for the whole service

Actual behavior

It would be nice if we could have the option to override per method. Let say I want the path parameter to be called slug for the get method and use the default id for the patch one

Please Provide Documentation/Make Example More Accessible

Two requests:

  1. Could you please provide documentation on how to use feathers-swagger? The instructions listed on the GitHub page are rather deficient (eg. they don't mention the example.html file, or anything about the public directory at all, but having a publicly-served example.htm file is critical to actually being able seeing the generated documentation)

  2. Could you please replace the Bower references on the example file with CDN versions? This would make it so that anyone could use example.htm "out of the box" instead of having to setup an entire client side environment (with Bower, jQuery, Backbone, Handlebars, etc.).

... or better yet, if you could provide a "base HTML file" that anyone could use to get (even an extremely basic) UI "out of the box", that would be really great. In fact, anything at all you can do to make it so that users can:

  1. npm install feathers-swagger
  2. add documentation to their feathers server/service
  3. not have to do anything else
  4. see web-based documentation of their server/service

that would be awesome.

Plural routes lead to unwanted model names

In general rest routes can be singular or plural: /user or /users. I have seen both in the past.
If using a plural route, it will lead to strange names with feathers-swagger: The single entity is called "users" and multiple entities are called "users list". This is awkward, but only a name of a definition in the swagger file. But it get's you generate code with swagger-codegen or comparable libraries. The names are used as they are and your User type will be a Users.

I think removing some the plural "s" on occurrence would be brittle. Is there a way to configure the name/tag instead of using the path? If not, it would be awesome to have the ability. Or there is perhaps a better solution.

Disabling methods

Is there any way to disable methods (at least from a custom doc)?

Add documantation for customization of path object

Currently, I see no way of editing the path object inside the servcie. Only the definitions get parsed.

It would be great to add some information to the path object e.g. to set possible responses.

it could look something like this:

class MessagesService {

  constructor(options) {
    this.options = options || {};

    this.docs = {
      description: 'A service to send messages',
      definitions: {
        messages: { (...) }
      }
      path: {
        messages: {
          create: {   // Anything inside would override the default config for "/messages".post
            description: 'Custom POST description',
            responses: {
              '201': {
                description: 'New Message was created'
              }
            }
          }
        }
      }
    }
  }

  (...)
}

Feature Idea: Validation

I just stumbled upon swagger-validate and found that this would actually be a great thing if feathers-swagger would come with a hook for validation, which can validate based on swagger.

Example apps only work when run from root of repo

Steps to reproduce

Run the example app from the it's actualy folder (ie. example/simple/).

Expected behavior

It should show the UI

Actual behavior

it doesn't

This is due to the UI being served from node_modules

Outdated provider signature w/ Buzzard

feathers-swagger uses the Auk & prior signature to create a new provider:

providers.push((path, service) => {});

Usage:
https://github.com/feathersjs-ecosystem/feathers-swagger/blob/master/src/index.js#L76

Reference in Auk:
https://github.com/feathersjs/feathers/blob/3756f99af7680b6e9e77b70d6e2f46efba1a6839/src/application.js#L49

This breaks in Buzzard, due to the swapping of path and service:

providers.push((service, path) => {});

Reference in Buzzard:
https://github.com/feathersjs/feathers/blob/d4688ca9874b242a9b453caddf117af27f8a0b01/lib/application.js#L115

A fix is to just swap the two parameters, however, I'm unsure how the Feathers team is handling 2.0 -> 3.0 breaking changes.

Versioned sub-app API does not produce docs

Hi,

Thanks for your great plugin!
Although it is great, I have been struggling to build docs for my API, built as a versioned sub-app.

const feathers = require('feathers');
const rest = require('feathers-rest');
const memory = require('feathers-memory');
const bodyParser = require('body-parser');
const swagger = require('feathers-swagger');

const messageService = memory();

messageService.docs = {
  description: 'A service to send and receive messages',
  definitions: {
    messages: {
      "type": "object",
      "required": [
        "text"
      ],
      "properties": {
        "text": {
          "type": "string",
          "description": "The message text"
        },
        "useId": {
          "type": "string",
          "description": "The id of the user that send the message"
        }
      }
    }
  }
};

const api = feathers()
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(rest())
  .use('/messages', messageService);

const app = feathers()
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(rest())
  .configure(swagger({
    docsPath: '/docs',
    info: {
      title: 'A test',
      description: 'A description'
    },
    prefix: '/api/v1',
    versionPrefix: '/v1',
    uiIndex: true
  }))
  .use('/api/v1', api);

app.listen(3000);

It should serve the following URIs:

  • docs: http://localhost:3000/docs
  • API: http://localhost:3000/api/v1/messages

Is that supported and, if it is, how may I do that properly?

Thank you very much,

Resolver error at paths./users.get.responses.200.schema.$ref

I keep getting this error:

Resolver error at paths./users.get.responses.200.schema.$ref
Could not resolve reference because of: Could not resolve pointer: /definitions/users list does not exist in document

Here is the code.

module.exports = function (app) {

  const paginate = app.get('paginate');

  let swaggerDocs = {
    description: 'Service for managing users',
    definitions: {
      users: {
        "type": "object",
        "required": [
          "username",
          "password"
        ],
        "properties": {
          "username": {
            "type": "string",
            "description": "The email of the user"
          },
          "password": {
            "type": "string",
            "description": "The password of the user for figo."
          }
        }
      }
    }

  }
  const options = {
    name: 'users',
    paginate,
    app: app
  };

  // Initialize our service with any options it requires
  app.use('/users', Object.assign(createService(options), { docs: swaggerDocs }));

  // Get our initialized service so that we can register hooks and filters
  const service = app.service('users');

  service.hooks(hooks);

};

What am I missing?

ENOENT: no such file or directory

I get the following error message: error: (ENOENT) Route: /docs/ - ENOENT: no such file or directory, stat '/usr/src/app/src/docs.html'

In my app.js I have put:

.configure(swagger({
    docsPath: '/docs',
    uiIndex: path.join(__dirname, 'docs.html'),
    info: {
      title: 'A test',
      description: 'A description'
    }
  }))

The feathers app runs in a docker container. I guess it has something to do with creating the docs.html within the container. When I remove the uiIndex:, I get the swagger json output under /docs/.

Documentation Doesn't Exist: What Boneheaded Thing Did I Do?

EDIT Please ignore this ticket. It turned out the bone-headed I did thing was trying to define the Swagger documentation after the middleware (which doesn't work because the 404 middleware takes over every route that hasn't been specified before it gets added).

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.