GithubHelp home page GithubHelp logo

surnet / swagger-jsdoc Goto Github PK

View Code? Open in Web Editor NEW
1.6K 11.0 224.0 2.88 MB

Generates swagger/openapi specification based on jsDoc comments and YAML files.

License: MIT License

JavaScript 97.26% CSS 2.74%
swagger jsdoc swagger-jsdoc openapi

swagger-jsdoc's Introduction

swagger-jsdoc

This library reads your JSDoc-annotated source code and generates an OpenAPI (Swagger) specification.

npm Downloads CI

Getting started

Imagine having API files like these:

/**
 * @openapi
 * /:
 *   get:
 *     description: Welcome to swagger-jsdoc!
 *     responses:
 *       200:
 *         description: Returns a mysterious string.
 */
app.get('/', (req, res) => {
  res.send('Hello World!');
});

The library will take the contents of @openapi (or @swagger) with the following configuration:

const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Hello World',
      version: '1.0.0',
    },
  },
  apis: ['./src/routes*.js'], // files containing annotations as above
};

const openapiSpecification = swaggerJsdoc(options);

The resulting openapiSpecification will be a swagger tools-compatible (and validated) specification.

swagger-jsdoc example screenshot

System requirements

  • Node.js 12.x or higher

You are viewing swagger-jsdoc v6 which is published in CommonJS module system.

Installation

npm install swagger-jsdoc --save

Or

yarn add swagger-jsdoc

Supported specifications

  • OpenAPI 3.x
  • Swagger 2
  • AsyncAPI 2.0

Validation of swagger docs

By default swagger-jsdoc tries to parse all docs to it's best capabilities. If you'd like to you can instruct an Error to be thrown instead if validation failed by setting the options flag failOnErrors to true. This is for instance useful if you want to verify that your swagger docs validate using a unit test.

const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  failOnErrors: true, // Whether or not to throw when parsing errors. Defaults to false.
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Hello World',
      version: '1.0.0',
    },
  },
  apis: ['./src/routes*.js'],
};

const openapiSpecification = swaggerJsdoc(options);

Documentation

Click on the version you are using for further details:

swagger-jsdoc's People

Contributors

a-morn avatar aleksey-a-maltsev avatar calmdev avatar chdanielmueller avatar daniloab avatar dependabot[bot] avatar dolphub avatar drgrove avatar efmr avatar ehmicky avatar fliptoo avatar goldsziggy avatar haegin avatar kalinchernev avatar kc-dot-io avatar mandrean avatar mits87 avatar nejclovrencic avatar posquit0 avatar relvao avatar rockingrohit9639 avatar sapegin avatar shady2k avatar spencermcw avatar sposmen avatar stelcheck avatar superflyxxi avatar tlvince avatar trendfischer avatar zeevo 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  avatar  avatar

swagger-jsdoc's Issues

How can I avoid this validation error?

I have docs that load on a site behind VPN. For obvious reasons, when I load the docs, I get that pesky red error display because the validator can't reach what it's trying to validate:

screen shot 2017-07-06 at 4 55 26 pm

Documentation is pretty sparse on this, but my understanding is that I can set a validatorUrl property to null. I just can't find anything that tells me where and everywhere I've tried doesn't seem to work. Here's the config that I'm passing to my swaggerDoc() with commented keys where I've tried inserting the validatorUrl setting:

{
    // validatorUrl: null,
    swaggerDefinition: {
        // validatorUrl: null,
        info: {
            // validatorUrl: null,
            title: 'Auth Service', // Required
            version: apiVersion, // Required
            description: ' ... '
        }
    },
    apis: [ './.swagger.js' ] // Path to the API docs
    // validatorUrl: null
}

Where am I going wrong?

[Maintainer] Maintenance questions

Hi @drGrove and @chdanielmueller,

There are few topics that I'd like to open for discussions. Your feedback is really welcome.

1) Releases and change log
Since the last 2 merge pull requests, I'm trying to maintain an automated change log with standard version. It's not perfect yet as it's necessary to include some sort of tagging of releases to make the explanations in the log more detailed. Yet, I am not able to push the small bumps in versions and change logs since some time.

2) ESLint
I'd like to integrate this mainly because it's very flexible, has good community support for presets and is also well integrated with many IDEs. Here's a comparison with pros and cons of other linting tools. The recently published prettier also integrates well with ESLint and Atom for example. This brings a really pleasant workflow.

3) The Node version to support
It's really honorable that the swagger-jsdoc module supports older versions of node. (not using ES2015 or newer language features) Though, the LTS schedule shows that it's not really necessary anymore as things have changed after the merge with io.js
I believe we can allow ourselves to use ES2015 features (like v4 or more) in the module safely enough at this point of time.
Similarly to ESLint adoption (with something like the airbnb preset) this change will bring better developer experience for the maintainers of the project.

4) Travis would be helpful having tests on several node versions
It's similar to CircleCI with the small and important difference that we can run several types of tests.

Most of these are non-blocking questions for me, rather things to discuss in direction how to lift up the developer experience on the project. What are your views on these?

[Maintainer] GitHub settings

Hi @kalinchernev and @drGrove

I was thinking about changing some of the repository settings and would like to get your feedback on this.

Since this project is pretty popular with over 30'000 downloads a month on npm I think it would be useful to protect the master branch. I would recommend the following settings to make sure we do not merge any faulty and unreviewed code.
branch protection

Furthermore it would be cool if we could decide on a merging style. I don't really have an opinion on the merging style but if there is the option to standardize the merges it might be useful.
merging settings

I am keen to hear your opinions.

Thanks,
Daniel

I have the problem with 'chokidar' package.

Hi!

I have installed swagger-json locally. When I try to use ./node_modules/.bin/swagger-json, an error occur.

module.js:472
    throw err;
    ^

Error: Cannot find module 'chokidar'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/stanislav/dev/test/swagger-jsdoc/node_modules/swagger-jsdoc/bin/swagger-jsdoc.js:14:16)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

I've found out that 'chokidar' package is using in devDependencies. Could you fix the problem?
Correct me please, if I'm wrong.

Using in typescript

Cannot install typings

typings install dt~swagger-jsdoc --global --save
typings ERR! message Unable to find "swagger-jsdoc" ("dt") in the registry.

Definition file should contain an info object!

Trying to run:

swagger-jsdoc.js -d swaggerdoc.js -o apidoc.json

and getting this error:

Definition file should contain an info object! More at http://swagger.io/specification/#infoObject

Here's my swaggerdoc.js definition file, not sure what's going on, I copied it from the examples I've seen here.


var options = {
  swaggerDefinition: {
    swagger: '2.0',
    info: {
      title: 'Animal Tracker', // Title (required)
      version: '1.0.0', // Version (required)
      description: '',
      contact: {
        name: '',
        url: ''
      }
    },
  },
  apis: ['./app/**/*.ts'], // Path to the API docs
};

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
var swaggerSpec = swaggerJSDoc(options);```

How to use this module with typescript?

Hi, guys
I'm writing my node-express app with typescript, I installed 'swagger-jsdoc' and '@types/swagger-jsdoc'. but when I want to import swagger-jsdoc by import * as swaggerJSDoc from 'swagger-jsdoc', an error occurs. error| Module '"swagger-jsdoc"' resolves to a non-module entity and cannot be imported using this construct. So, how to use this module with typescript?

post an array of string in formData

when i try to post an array of string in formData
swagger add double quotes Ex: [ ""Value"" ]

/**
 * @swagger
 * /accessories-centers:
 *   post:
 *     tags:
 *       - Accessories-Centers
 *     consumes:
 *       - "multipart/form-data"
 *     summary: Create a new Accessories center
 *     parameters:
 *           - name: "mainSpecialities[]"
 *             in: "formData"
 *             description: "Ids Main Specialities Of accessories center"
 *             required: false
 *             collectionFormat: multi
 *             type: array
 *             items:
 *                  type: string
 *     responses:
 *       201:
 *         description: Returns Created accessories-Center
 */

Output:
Network Image
[ '"id1","id2"' ]

Deprecate 'tag'

Tag should be fully deprecated in favor of tags, as it aligns with the Swagger v2.0 spec

Need way to turn off deprecation warnings

I am trying to document my API and am creating some schemas for body properties. One of the properties you can send in the body is named 'path', but when using swagger-jsdoc to generate the spec, I'm getting an error:

You are using properties to be deprecated in v2.0.0
Please update to align with the swagger v2.0 spec.
[ 'path' ]

Looking through the code it looks like you are finding deprecated properties from the old spec and spitting out a warning if you see any property matching it even if it's a valid property.

It would be nice to have a way to tell swagger-jsdoc that "hey I know what I'm doing, please turn off deprecation warnings".

And also it might be good to check if passed in properties are actual properties instead of denying it based solely on the property name.

I could submit a PR for this feature if you give me some direction on how you'd like to see it implemented.

Thanks!

swagger doc is not creating.

Swagger doc is not creating. Just following is displaying.
{"info":{"title":"Node Swagger API","version":"1.0.0","description":"Demonstrating how to desribe a RESTful API with Swagger"},"host":"localhost:3000","basePath":"/","swagger":"2.0","paths":{},"definitions":{},"responses":{},"parameters":{},"securityDefinitions":{},"tags":[]}

Supporting multiple paths with CLI?

Is it possible to watch multiple directories when executing swagger-jsdoc from CLI?
Currently have to resort to writing custom script and executing it with node like this..

var swaggerJSDoc = require('swagger-jsdoc');
var options = {
	swaggerDefinition: {
		info: {
			title: 'API',
			version: '1.0.0',
			description: '',
		},
		host: 'https://api.xxx.com', // Host (optional)
		basePath: '/v1', // Base path (optional)
	},
	apis: ['apps/controllers/*.js', 'apps/entities/*.js'],
};
var swaggerSpec = swaggerJSDoc(options);
require('fs').writeFile('api.json', JSON.stringify(swaggerSpec, null, 4));

Code doesn't merge path objects from different files.

I'm working on a serverless api. The folder structure separates the api by path and then individual files to represent the operations and thus the http method. This means two comments regarding a path occur in two separate files, but they have different http methods (GET, PUT, etc). When I generate the JSON swagger doc the last file read has its properties in the same file.

In _organizeSwaggerProperties in swagger-helper.js the first conditional statement would trigger for path/paths, and it doesn't merge objects, thus the last read object would over write the previous state. Should this be patched to the below code where the objects are merged:

if (simpleProperties.indexOf(propertyName) !== -1) {

    var keyName = _correctSwaggerKey(propertyName);
    var definitionNames = Object
      .getOwnPropertyNames(pathObject[propertyName]);
    for (var k = 0; k < definitionNames.length; k = k + 1) {
      var definitionName = definitionNames[k];

      // Notice the merge function call here.
      swaggerObject[keyName][definitionName] =
        _objectMerge(swaggerObject[keyName][definitionName], pathObject[propertyName][definitionName]);
    }
  // Tags.
  }

how to add requestBody into doc

/**
 * @swagger
 * /test:
 *   post:
 *     summary: test
 *     description: test
 *     tags: [deal]
 *     produces:
 *       - application/json
 *     parameters:
 *       - name:_id
 *         description:  Id
 *         in: formData
 *         required: true
 *         type: String
 *     requestBody:
 *       - content:
 *         'application/json':
 *           schema: # Request body contents
 *             id:
 *               type: integer
 *             name:
 *               type: string
 *             example: # Sample object
 *               id: 10
 *               name: Jessica Smith
 *     responses:
 *       200:
 *         description: '{}'
 */

I tried to add requestBody into doc, but not work

Feature request: options.apis allows globs in addition to full file paths

This would be useful for projects that have lots routes/controllers broken up into many files. Also, when a new route module is introduced to the project, we will not need to add its path to the array.

Example:

var swaggerJSDoc = require('swagger-jsdoc');

var options = {
  swaggerDefinition: {
    info: {
      title: 'Hello World', // Title (required)
      version: '1.0.0', // Version (required)
    },
  },
  apis: ['./routes/*.js'], // Path to the API docs
};

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
var swaggerSpec = swaggerJSDoc(options);

If this would be a useful addition, I would be happy to submit a PR.

Add support for Swagger tags

This does not seem to work:

/**
 * @swagger
 * tag:
 * ...
 */

Would be great if this syntax was supported (similar to definitions/parameters/etc).

How to specify auth

I've created a node server and a documenting the API with swagger using swagger-jsdoc. I'm using Auth0 for authentication and would like to be able to tell swagger about it so it can pass the right information to the APIs.

How can I do that?

Swagger-node has a solution, but that is for swagger-node: swagger-api/swagger-node#421

allOf is not working

Hi I'm testing with this example from OpenAPI Specification but the result is an empty object in Swagger UI.

Code:

definitions:
  ErrorModel:
    type: object
    required:
    - message
    - code
    properties:
      message:
        type: string
      code:
        type: integer
        minimum: 100
        maximum: 600
  ExtendedErrorModel:
    allOf:
    - $ref: '#/definitions/ErrorModel'
    - type: object
      required:
      - rootCause
      properties:
        rootCause:
          type: string

Result:

untitled-1

SwaggerDefinition cannot support tags

swaggerDefinition like following.

swaggerDefinition: {
    info: {
      'title': 'Hello Word',
      'description': 'This is a sample server Petstore server.',
      'termsOfService': 'http://www.google.com',
      'contact': {
        'name': 'Trigether API Doc',
        'url': 'http://www.google.com',
        'email': '[email protected]'
      },
      'version': '0.0.1'
    },
    tags:[
      {
        'name': 'user',
        'description': 'User APIs'
      },
      {
        'name': 'setting',
        'description': 'Setting APIs'
      }
    ],
    basePath: '/api'
  }

After generate json,

{  
   "info":{  
      "title":"Hello Word",
      "description":"This is a sample server Petstore server.",
      "termsOfService":"http://www.google.com",
      "contact":{  
         "name":"Trigether API Doc",
         "url":"http://www.google.com",
         "email":"[email protected]"
      },
      "version":"0.0.1"
   },
   "tags":[  

   ],
   "basePath":"/api",
   "swagger":"2.0",
}

tags is empty

Coffee Script Support

/** @module index */
'use strict';

// Dependencies
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var doctrine = require('doctrine');
var jsYaml = require('js-yaml');
var parser = require('swagger-parser');
var swaggerHelpers = require('./swagger-helpers');

/**
 * Parses the provided API file for JSDoc comments.
 * @function
 * @param {string} file - File to be parsed
 * @returns {{jsdoc: array, yaml: array}} JSDoc comments and Yaml files
 * @requires doctrine
 */
function parseApiFile(file) {
  var jsDocRegex = /\/\*\*([\s\S]*?)\*\//gm;
  var csDocRegex = /\#\#\#([\s\S]*?)\#\#\#/gm;
  var fileContent = fs.readFileSync(file, { encoding: 'utf8' });
  var ext = path.extname(file);
  var yaml = [];
  var jsDocComments = [];
  var regexResults = null;

  if (ext === '.yaml' || ext === '.yml') {
    yaml.push(jsYaml.safeLoad(fileContent));
  } if (ext === '.coffee') {
    regexResults = fileContent.match(coffeeDocRegex);
  } else {
    regexResults = fileContent.match(jsDocRegex);
  }
  if (regexResults) {
    for (var i = 0; i < regexResults.length; i = i + 1) {
      var jsDocComment = doctrine.parse(regexResults[i], { unwrap: true });
      console.log(jsDocComment);
      jsDocComments.push(jsDocComment);
    }
  }

  return {
    yaml: yaml,
    jsdoc: jsDocComments,
  };
}

/**
 * Filters JSDoc comments for those tagged with '@swagger'
 * @function
 * @param {array} jsDocComments - JSDoc comments
 * @returns {array} JSDoc comments tagged with '@swagger'
 * @requires js-yaml
 */
function filterJsDocComments(jsDocComments) {
  var swaggerJsDocComments = [];

  for (var i = 0; i < jsDocComments.length; i = i + 1) {
    var jsDocComment = jsDocComments[i];
    for (var j = 0; j < jsDocComment.tags.length; j = j + 1) {
      var tag = jsDocComment.tags[j];
      if (tag.title === 'swagger') {
        swaggerJsDocComments.push(jsYaml.safeLoad(tag.description));
      }
    }
  }

  return swaggerJsDocComments;
}

/**
 * Converts an array of globs to full paths
 * @function
 * @param {array} globs - Array of globs and/or normal paths
 * @return {array} Array of fully-qualified paths
 * @requires glob
 */
function convertGlobPaths(globs) {
  return globs.reduce(function(acc, globString) {
    var globFiles = glob.sync(globString);
    return acc.concat(globFiles);
  }, []);
}

/**
 * Generates the swagger spec
 * @function
 * @param {object} options - Configuration options
 * @returns {array} Swagger spec
 * @requires swagger-parser
 */
module.exports = function(options) {
  /* istanbul ignore if */
  if (!options) {
    throw new Error('\'options\' is required.');
  } else /* istanbul ignore if */ if (!options.swaggerDefinition) {
    throw new Error('\'swaggerDefinition\' is required.');
  } else /* istanbul ignore if */ if (!options.apis) {
    throw new Error('\'apis\' is required.');
  }

  // Build basic swagger json
  var swaggerObject = swaggerHelpers.swaggerizeObj(options.swaggerDefinition);
  var apiPaths = convertGlobPaths(options.apis);

  // Parse the documentation in the APIs array.
  for (var i = 0; i < apiPaths.length; i = i + 1) {
    var files = parseApiFile(apiPaths[i]);
    var swaggerJsDocComments = filterJsDocComments(files.jsdoc);

    var problems = swaggerHelpers.findDeprecated([files, swaggerJsDocComments]);
    // Report a warning in case potential problems encountered.
    if (problems.length > 0) {
      console.warn('You are using properties to be deprecated in v2.0.0');
      console.warn('Please update to align with the swagger v2.0 spec.');
      console.warn(problems);
    }

    swaggerHelpers.addDataToSwaggerObject(swaggerObject, files.yaml);
    swaggerHelpers.addDataToSwaggerObject(swaggerObject, swaggerJsDocComments);
  }

  parser.parse(swaggerObject, function(err, api) {
    if (!err) {
      swaggerObject = api;
    }
  });

  return swaggerObject;
};

Made some slight modifications to your index.js file in order to support coffeescript block comments. With the changes above you can do the following:

# Coffeescript Example

###
* @swagger
* /login:
*   post:
*     description: Login to the application
*     produces:
*       - application/json
*     parameters:
*       - name: username
*         description: Username to use for login.
*         in: formData
*         required: true
*         type: string
*       - name: password
*         description: User's password.
*         in: formData
*         required: true
*         type: string
*     responses:
*       200:
*         description: login
###
app.post '/login', (req, res) ->
  res.json req.body

Can I get added as a collaborator so I can build out more coffee support into this very helpful module?

Cheers!

Update documentation for usage

When specifying the path to the api routes, it currently requires relative to where node is started from and NOT from the app.js. Please clarify this in documentation. I've read several articles that all claim it is relative to the app.js which is incorrect. I spent about 4 hours tinkering around before I happened upon a helpful closed Issue where someone found the same

var options = {
  swaggerDefinition: {
    info: {
      title: 'Hello World',
      version: '1.0.0',
    },
  },
  apis: ['./api/routes/*.js'], // Path to the API docs RELATIVE TO NODE START AND NOT APP.JS
};

Problem with deep directories

Hi,

swagger-jsdoc doesn't generate the documentation for files in "deep" directories. I don't know if it's a bug from glob or swagger-jsdoc.

Here is my file structure :

.
|- scripts/
|
| - src/
|    |
|    | - controllers/
|    |    |
|    |    | - projects/
|    |    |    |
|    |    |    | - index.js
|    |    |
|    |    | - index.js

I have added commands in my package.json file

"doc": "swagger-jsdoc -d scripts/swaggerDef.js -o ../documentation/public/swagger.json ./src/**/*.js",
"doc:watch": "yarn run doc -- -w"

And here is my swaggerDef.js file :

const packageJson = require('../package.json')

const tagNames = 'blueprint invitation notification org ' +
    'project-tag user project task'

const tags = tagNames
                .split(' ')
                .map(name => {
                    return {
                        name,
                    }
                })

module.exports = {
    info: {
        title: 'Clovis API',
        version: packageJson.version,
        description: 'Official Clovis API documentation.',
    },
    host: 'localhost:3009',
    tags,
}

When I run swagger-jsdoc only src/controllers/index.js is processed, not src/controller/projects/index.js

I run the yarn run doc from the root of my project.

Support for multiline comments without leading asterisk

Request

Add support for documentation styles like

/**
  @swagger
  /ratings/{targetNamespace}:
    get:
      summary: List ratings in a given target namespace.
      description: |
          List ratings in a given target namespace.
          If requesting as a service user, unpublished ratings
          will not be returned.
   ...
**/

which currently break with various errors. swagger-jsdoc apparently expects every line to start with an asterisk symbol and therefore fails to parse multiline parameters properly.

Reasoning

Leading asterisk characters can be very confusing for most editors. The editor fails to notice the indentation levels of the documentation due to the asterisk characters and managing the indentations becomes tedious. Also, some editors don't automatically add the asterisk when adding a new line which only adds to the manual work.

Not only that, but when writing comments like

/*
 * line1
 *   line2
 */

line1 has 3 characters before it and line2 has 5. This causes a bit of issues since standard indentations are usually 4 and 6 and the editor doesn't realise this, "missing" the right indentation level when pressing tab. The last space has to be added separately. It's possible to write like

/*
* line1
*   line2
*/

but this looks rather ugly IMO.

Example

The following works:

  /**
   * @swagger
   * '/data':
   *    get:
   *      description: List data
   *      produces:
   *        - application/json
   *      responses:
   *        '200':
   *          description: Data
   */

And the following currently fails:

  /**
    @swagger
    '/data':
       get:
         description: List data
         produces:
           - application/json
         responses:
           '200':
             description: Data
   */

with an error:

<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:171
  throw generateError(state, message);
  ^
YAMLException: duplicated mapping key at line 8, column 1:
    description: Data
    ^
    at generateError (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:165:10)
    at throwError (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:171:9)
    at storeMappingPair (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:308:7)
    at readBlockMapping (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1071:9)
    at composeNode (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1332:12)
    at readDocument (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1492:3)
    at loadDocuments (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1548:5)
    at load (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1569:19)
    at Object.safeLoad (<PATH_TO_PROJECT>/node_modules/js-yaml/lib/js-yaml/loader.js:1591:10)
    at filterJsDocComments (<PATH_TO_PROJECT>/node_modules/swagger-jsdoc/lib/index.js:60:42)
    at module.exports (<PATH_TO_PROJECT>/node_modules/swagger-jsdoc/lib/index.js:106:32)
...

Passing an array of schemas not working

I'm trying to include something like the following, but when I send my array of schemas, the json body is line delimited, which I don't understand.

screen shot 2016-08-02 at 9 23 36 pm

Any help is appreciated.

  /**
   * @swagger
   * /api/v1/words/sample/:
   *   post:
   *     tags:
   *       - WordSamples
   *     description: Creates word samples. segments the words by hour increments, on the hour
   *       <table>
   *       <tr>
   *       <td>db</td>
   *       <td>sql check</td>
   *       <tr>
   *       <td>postgres</td>
   *       <td>SELECT * FROM "WordSamples" WHERE "childId" = "childId"</td>
   *       </tr>
   *       <tr>
   *       <td>dynamo</td>
   *       <td>look for local-WordSamples</td>
   *       </tr>
   *       </table>
   *     consumes:
   *       - application/json
   *     produces:
   *       - application/json
   *     parameters:
   *     - name: Auth
   *       in: header
   *       description: jwt
   *       required: true
   *       type: string
   *       format: string
   *     - name: wordSamples
   *       description: Input array of word sample dictionaries
   *       in: body
   *       required: true
   *       type: "array"
   *       items:
   *         $ref: "#/definitions/WordSamples"
   *     responses:
   *       200:
   *         description: returns the number of inserts and insertedAt, which can be used
   *           to filter selects
   */

[Maintainer] Signing Tags

Due to #63 being opened, this has lead me to think we should start GPG signing tags. This will ensure to our end users that we have verified what is in a tag (Why Sign Tags). We can also set npm to handling this with the npm version command using sign-git-tag config

[Maintainer] Open API spec

I'll use the opportunity and the recent maintainers' activity to rise another high-level question I think will be good to start considering: the upcoming update in the swagger specification which becomes open api spec.

The situation we have at the moment as I see it is as following.

Community

High-level observations:

  • v3 rc was released recently, which probably means it's a good time to open the discussion
  • research efforts on tooling migration also has started by a prominent figure in the community
  • I think that with good strategy, swagger-jsdoc could target a good positioning in the documentation segment of the open api spec toolchain. Could also be in a general tooling of node.js, though I think that the momentum of the last year could be used as an advantage to seek a concrete positioning and purpose.

Although I'm not having the opportunity to be a full-time API architect or developer, the little time I manage to get from side projects and prototyping tasks, I already feel that swagger-jsdoc could be a useful tool when documentation in code can be reused as documentation out of code.

For example, here are 2 experiments I've been having recently:

As you can see, the workflows I'm experimenting with are going around the specification as core reusable component, and then trying to integrate swagger-jsdoc or other tool in "watch" mode to speed up the development of the spec together with the documentation generation and deployment.

Technical aspect

The 2 core dependencies this module has are doctrine and swagger-parser. So, I don't think we have to worry too much for these dependencies as probably we'll need to conditionally exchange only the swagger-parser or just use it as-is, depending on how it'll progress on the new specification.

Another question and aspect would be, would this plugin aim to handle 2 specifications at the same time? If yes, I think that i'd be convenient to change the way the module is used just a bit

var swaggerSpec = swaggerJSDoc(options);

to something like

// Get the module
const swaggerJsdoc = require('swagger-jsdoc');
// Create a parser depending on the specification and type of documentation blocks
const openApiDocsParser = swaggerJsdoc.createParser({version: 3, comments: jsdoc});
// Continue as now
const openApiSpec = openApiDocsParser(options);
// Or accept CPS
openApiDocsParser(options, spec => fs.writeFile('openapi.yaml', spec));

What I basically have in mind is that we can create a simple factory accepting some options before constructing the parser in order to be open for both new versions of the specification and different documentation styles if we would.

Your comments and feedback are welcome!


PS:

Include filepath of offender on warning/errors

In my case I have the jsdoc aside the code, so i have spread a lot of jsdoc comments everywhere, it would be nice if the file path is include withtin the message

You are using properties to be deprecated in v2.0.0
Please update to align with the swagger v2.0 spec.
[ 'response' ]

apis deep paths

I had this working with a default express install
but now I moved my directory to match

apis: [ './express/routes/*.js', '../lib/models/*.js' ]

I don't get any errors but no swagger objects are made except for my definition, which serves up fine.

Am I doing something wrong for this type of setup?

Use JavaScript POJOs in definitions

Good job on what you do on this project. I was wondering if it was possible to use POJOs in definitions instead of copying the properties.

Let's say I have a POJO

function UserProfile(email, firstName, lastName) {
    this.email = email;
    this.firstName = firstName;
    this.lastName = lastName;
};

Currently in the definition I have to repeat the fields

/**
 * @swagger
 * definitions:
 *   UserProfile:
 *     properties:
 *       email:
 *         type: string
 *       firstName:
 *         type: string
 *       lastName:
 *         type: string
 */

Do you think it is conceivable to use something like this :

const UserProfile = require('../models/user-profile');

/**
 * @swagger
 * definitions:
 *   UserProfile:
 *     $ref: 'UserProfile'
 */

That would be awesome. I could work on a PR if it is possible.
Thanks.

"Lite" version of swagger-jsdoc - exlude `cli` version

Hi!

My builds are becoming quite heavy when using swagger-jsdoc primarily due to the reason that it using chokidar which depends on fsevents which depends on node-gyp.

node-gyp needs to be re-compiled on Unix / OS X from time to time when I do my installs and this takes forever.
Looking deeper into the code - that functionality used only by the CLI version of swagger-jsdoc, so I though - maybe we could split this project into 2 - one purely for generating the docs, and another - purely for CLI purposes, which could depend on the first one as "binary" dependency.

What do you think?

Writing jsdoc in YAML is very difficult with comments

I liked this module however when I tried to use it for my API then it became nightmare as its very difficult to hand code JSDoc in YAML style. Very tough to write valid YAML syntax inside the comments.

Can I used any other comment format?

swagger-jsdoc doesn't work on node 0.10, as of release 1.2.0

I get this error when using the new swagger-jsdoc release on node.js v0.10.25, which is the default node.js install for the current Ubuntu LTS release.

I believe this is related to swagger-jsdoc using path.parse, which has become available in node 0.12.

Upgrading to node.js 0.12 or newer solves the issue, as does downgrading to swagger-jsdoc 1.1.2.

zoek-werkplek-api-0 (err): TypeError: Object #<Object> has no method 'parse'
zoek-werkplek-api-0 (err):     at parseApiFile (/opt/build/microservices/zoek-werkplek-api/node_modules/swagger-jsdoc/lib/index.js:23:18)
zoek-werkplek-api-0 (err):     at module.exports (/opt/build/microservices/zoek-werkplek-api/node_modules/swagger-jsdoc/lib/index.js:158:17)

Header value is not transferred properly to express app controller from Swagger-ui

I am having a routes section updated with swagger jsdoc comments as given below; The UI is generating fine and I can serve the static swagger-UI in express app. But when I am accessing the route

http://localhost:3000/api/v1/users with token in the head parameter ; the token is received in my express controller but perceived as undefined

error-swagger-jsdoc

When I am using postman client though it is working fine and returning me the user array.

postman

I am new to swagger please suggest me what to do or where I am making the mistake.

router.all('*', userControllers.isAuthenticated);

 /**
 * @swagger
 * definition:
 *   User:
 *     type: object
 *     properties:
 *       firstName:
 *         type: string
 *       lastName:
 *   Users:
 *     allOf:
 *       - $ref: '#/definitions/User'
 *         properties:
 *          _id:
 *            type: string
 *          apiToken:
 *            type: string
 *
 */

/**
 * @swagger
 * /api/v1/users:
 *   get:
 *     tags:
 *       - Users
 *     description: Returns all users
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: x-api-token
 *         description: Token for auth
 *         in:  head
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: An array of users
 *         schema:
 *           type: array
 *           items:
 *              $ref: '#/definitions/Users'
 */
router.get('/users', policies.isAllowed, userControllers.getUsers);

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.