Code Monkey home page Code Monkey logo

sails-hook-swagger-generator's Introduction

Swagger Generator Sails Hook

Travis npm npm npm semantic-release

This helps to create swagger documentation json which is based entirely on Swagger/OpenAPI specification (see here). The hook produces specification based upon OAS 3.0.

Installation

$ npm install sails-hook-swagger-generator --save

Demo

Copy the content of generatedSwagger and paste it in Swagger Online Editor.

Usage

Simply by lifting your sails app sails lift, after lifting or starting the app,there should be swagger.json within ./swagger folder.

make sure ./swagger folder is already existing.

Check the ./swagger/swagger.json for generated swagger documentation json, then head to Swagger Editor.

Generated Output

By default, the Swagger Generator Sails Hook generates:

  1. Full automatic documentation for all Sails Blueprint routes;
  2. Documentation for all Sails actions2 actions with routes configured in config/routes.js; and
  3. Listing of all routes configured in config/routes.js (full details cannot be inferred for custom routes without additional information being provided - see below).
  4. Creation of default tags for paths based upon Sails Model and Controller globalId's.

Use with Swagger UI

See #28

Adding/Customising Generated Output

Documentation detail and customisation of most aspects of the generated Swagger can be achieved by adding:

  1. Top-level configuration to config/swaggergenerator.js. This provides direct JSON used as the template for the output Swagger/OpenAPI.
  2. Objects with the key swagger to custom route configuration, controller files, action functions, model definitions and model attribute definitions. The swagger element must be of type SwaggerActionAttribute for actions (based on OpenApi.Operation) or SwaggerModelSchemaAttribute for model schemas (based on OpenApi.UpdatedSchema).
  3. JSDoc (swagger-jsdoc) @swagger comments to controller/action files and model files.

Top-level Swagger/OpenAPI definitions for tags and components may be added in all swagger objects above and in all JSDoc @swagger documentation comments. This enables the definition of top-level elements.

See below for details.

Configurations

It comes with some default settings which can be overridden by creating config/swaggergenerator.js:

module.exports['swagger-generator'] = {
    disabled: false,
    swaggerJsonPath: './swagger/swagger.json',
    swagger: {
        openapi: '3.0.0',
        info: {
            title: 'Swagger Json',
            description: 'This is a generated swagger json for your sails project',
            termsOfService: 'http://example.com/terms',
            contact: {name: 'Theophilus Omoregbee', url: 'http://github.com/theo4u', email: '[email protected]'},
            license: {name: 'Apache 2.0', url: 'http://www.apache.org/licenses/LICENSE-2.0.html'},
            version: '1.0.0'
        },
        servers: [
            { url: 'http://localhost:1337/' }
        ],
        externalDocs: {url: 'https://theoomoregbee.github.io/'}
    },
    defaults: {
        responses: {
            '200': { description: 'The requested resource' },
            '404': { description: 'Resource not found' },
            '500': { description: 'Internal server error' }
        }
    },
    excludeDeprecatedPutBlueprintRoutes: true,
    includeRoute: function(routeInfo) { return true; },
    updateBlueprintActionTemplates: function(blueprintActionTemplates) { ... },
    postProcess: function(specifications) { ... }
};

Notes on the use of configuration:

  • disabled attribute is used to disable the module (e.g you may want to disable it on production).
  • swaggerJsonPath where to generate the swagger.json file to; defaults to sails.config.appPath + '/swagger/swagger.json' and output file will not be written if empty/null/undefined (see postProcess below for alternate save mechanism).
  • swagger object is template for the Swagger/OpenAPI output. It defaults to the minimal content above. Check Swagger/OpenAPI specification for more, in case you want to extend it. Generally, this hook provides sensible defaults for as much as possible but you may override them in this location or in any of the mechanisms explained below.
  • defaults object should contain the responses element; defaults to the above if not specified.
  • excludeDeprecatedPutBlueprintRoutes should deprecated PUT blueprint routes be excluded from generated Swagger output; defaults to true.
  • includeRoute function used to filter routes to be included in generated Swagger output; see advanced section below.
  • updateBlueprintActionTemplates allows customisation of the templates used to generate Swagger for blueprints; see advanced section below.
  • postProcess allows an alternate mechanism for saving and/or modification of the generated Swagger output before it is written to the output file; see advanced section below.

Custom Route Configuration

Documentation detail and customisation of most aspects of the generated Swagger for custom routes may be achieved by:

  1. Adding an object with the key swagger (must be of type SwaggerActionAttribute for actions, based on OpenApi.Operation) to individual route configurations in config/routes.js.
  2. Adding an object with the key swagger (must be of type SwaggerControllerAttribute) to the exports of a controller file, standalone action file or actions2 file.
  3. Adding an object with the key swagger (must be of type SwaggerModelAttribute) to the exports of a model file.
  4. Adding JSDoc @swagger comments to Sails model files, controller files, standalone action files or actions2 files; specifically:
    • JSDoc @swagger documentation under the /{actionName} path for the route (controllers/actions), or
    • JSDoc @swagger documentation under the /{blueprintAction} path for the route (models), or
    • JSDoc @swagger documentation under tags and components paths for adding to the top-level Swagger/OpenAPI definitions.

Custom Route Configuration in config/routes.js

If you want to add extra configuration to a route, it can be done via the config/routes.js, since Sails uses different route targets, we can leverage the route object target to extend/override our swagger configuration by adding an object with a key swagger.

For example, in config/routes.js:

{
  'post /user/login': {
    controller: 'UserController',
    action: 'login',
    swagger: {
      summary: 'Authentication',
      description: 'This is for authentication of any user',
      tags: [ 'Tag Name' ],
      requestBody: {
        content: {
          'application/json': {
            schema: {
              properties: {
                email: { type: 'string' },
                password: { type: 'string', format: 'password' }
              },
              required: [ 'email', 'password' ],
            }
          }
        }
      },
      parameters: [{
        in: 'query',
        name: 'firstName',
        required: true,
        schema: { type: 'string' },
        description: 'This is a custom required parameter'
      }],
      responses: {
        '200': {
          description: 'The requested resource',
            content: {
              'application/json': {
                schema: {
                  type: 'array',
                  items: { '$ref': '#/components/schemas/someDataType' },
                },
              },
            },
        },
        '404': { description: 'Resource not found' },
        '500': { description: 'Internal server error' }
      }
    }
  }
}

Custom Route Configuration in Controller or Action files

Documentation detail and customisation of most aspects of the generated Swagger may be added to controller files, standalone action files or actions2 files as follows:

  1. Adding an object with the key swagger added to a controller file action function.
  2. Adding an object with the key swagger to the exports of a controller file, standalone action file or actions2 file:
    • For controller files, actions are referenced by adding objects keyed on swagger.actions.{actionName} name. See UserController.js;
    • For standalone action or actions2 files, placing content in the swagger.actions.{actionFileName|actions2FileName} object. See actions2.js Note: actionFileName|actions2FileName must correspond to the filename;
    • For all controller/action files, adding per-action documentation to be applied to all actions using the key swagger.actions.allActions e.g. use this to apply common tags to all actions for a controller.
    • Adding documentation under tags and components elements for adding to the top-level Swagger/OpenAPI definitions. See example in either UserController.js or actions2.js.
  3. Adding JSDoc @swagger comments to controller file, standalone action file or actions2 file:
    • JSDoc @swagger documentation under the /{actionName} path for the controller file actions,
    • JSDoc @swagger documentation under the /{actionFileName|actions2FileName} path for standalone action or actions2 files,
    • JSDoc @swagger documentation under the /allActions path to be applied to all actions for the controller, or
    • JSDoc @swagger documentation under tags and components paths for adding to the top-level Swagger/OpenAPI definitions.

An exclude property, set to true, may be added to any swagger element or @swagger JSDoc action documentation to exclude that action from the generated Swagger. See example in NomodelController.js.

The Swagger definition for each action is merged in the order above to form the final definition, with config/routes.js taking highest precendence and earlier definitions above taking precedence over later.

For actions2 files:

  1. Inputs are parsed to generate parameter documentation.
  2. Exits are parsed to generate response documentation.
  3. Both may be customised/overridden by specifying parameters and/or responses in the swagger object in actions2 file.
  4. Inputs may also add an object with the key meta.swagger to document the attributes Swagger/OpenAPI schema associated with the input value. See example in actions2.js.
  5. Inputs may be excluded from the generated Swagger by setting meta.swagger.exclude to true.
  6. Inputs may specify where the input should be included within the generated Swagger using the key meta.swagger.in. The values query/header/path/cookie may be used to produce Swagger operation parameters and the value body may be used to produce requestBody schema properties (valid for PUT/POST/PATCH operations only).

For example, for a route configured as:

module.exports.routes = {
    '/api/v1/auth/tokens': 'AuthController.tokens',
};

The tokens action might be documented in a Controller api/controllers/AuthController.js as follows:

function tokens(req, res) {
    ...
}

module.exports = {
    tokens: tokens,
    swagger: {
      actions: {
        tokens: {
            tags: [ 'Auth' ],
            description: 'Route description...'
        }
      }
      tags: [
             {
                name: 'Auth',
                description: 'Module description ...',
             }
        ],
      components: {
        ...
      }
    }
};

Or, alternately using JSDoc:

/**
 * @swagger
 *
 * /tokens:
 *   description: Route description...
 *   tags:
 *     - Auth
 * tags:
 *   - name: Auth
 *     description: Module description...
 */
function tokens(req, res) {
    ...
}

module.exports = {
    tokens: tokens
};

Blueprint Route Configuration

Documentation detail and customisation of most aspects of the generated Swagger for blueprint routes may be achieved by:

  1. Adding an object with the key swagger to individual models e.g. api/models/modelName.js:
    • Adding documentation to the model's Swagger schema using the key swagger.modelSchema e.g. use this to apply detailed documentation via the description field;
    • In additon to the model's schema, the key swagger.modelSchema may be used to specify tag names (as a string[]) to be assigned all blueprint actions for the model. This is a non-standard convenience function i.e. in Swagger/OpenAPI you need to explicitly add tags to each/every OpenAPI.Operation;
    • Adding per-action documentation by adding objects keyed on swagger.actions.{blueprintAction} name;
    • Adding action documentation to all actions using the key swagger.actions.allActions e.g. use this to apply common externalDocs to all blueprint actions for the model; or
    • Adding documentation under swagger.tags and swagger.components elements for adding to the top-level Swagger/OpenAPI definitions.
  2. Adding documentation-specific fields to model attributes (supports description, moreInfoUrl and example). Note that applicable Sails attributes, automigrations and validations are also parsed.
  3. Adding an object with the key meta.swagger to individual model attributes to document the attributes Swagger/OpenAPI schema. See example in Pet.js.
  4. Adding JSDoc @swagger comments to model files:
    • JSDoc @swagger documentation under the /{globalId} to add documentation to the model's Swagger schema (or tags as noted above),
    • JSDoc @swagger documentation under the /{blueprintAction} to add per-action documentation for the model blueprint actions,
    • JSDoc @swagger documentation under the /allActions path to be applied to all blueprint actions for the model, or
    • JSDoc @swagger documentation under tags and components paths for adding to the top-level Swagger/OpenAPI definitions.

An exclude property, set to true, may be added to any swagger element of @swagger JSDoc action documentation to exclude the model completely (exclude the schema) or a specific blueprint action from the generated Swagger. See example in OldPet.js.

Individual model attributes may be excluded from the generated Swagger by setting meta.swagger.exclude to true. See example in Pet.js.

OpenAPI 3 specifies the Any Type by the absence of the type property in a schema; this may be achieved by setting a model attribute's meta.swagger.type value to null. See example in User.js.

The Swagger definition for each action is merged in the order above to form the final definition, with config/routes.js taking highest precendence and earlier definitions above taking precedence over later.

For example, in a model api/models/User.js:

/**
 * @swagger
 *
 * /User:
 *   tags:
 *     - Tag Name
 * /findone:
 *   externalDocs:
 *     url: https://docs.com/here
 */
module.exports = {
  attributes: {
    uid: {
      type: 'string',
      example: '012345',
      description: 'A unique identifier',
    }
  },
  swagger: {
    actions: {
      create: { ... },
    },
    modelSchema: { ... },
    tags: [...]
    components: {...}
  }
};

Note that following parameters are added to the components/parameters if they are not provided in config/swaggergenerator.js (expressed as OpenAPI references):

[
  { $ref: '#/components/parameters/WhereQueryParam' },
  { $ref: '#/components/parameters/LimitQueryParam' },
  { $ref: '#/components/parameters/SkipQueryParam' },
  { $ref: '#/components/parameters/SortQueryParam' },
  { $ref: '#/components/parameters/SelectQueryParam' },
  { $ref: '#/components/parameters/PopulateQueryParam' },
]

Note that when generating Swagger/OpenAPI documentation for blueprint routes, the hook also generates:

  1. Schemas for models, which may be referenced using the form { $ref: '#/components/schemas/modelName' }.
  2. Parameters for model primary keys, which may be referenced using the form { $ref: '#/components/parameters/ModelPKParam-modelName' }.

These may be re-used (referenced) if/as applicable within custom route documentation.

Handling Top-Level Swagger Defintions (Tags and Components)

You are able to add to the top-level Swagger/OpenAPI definitions for tags and components in all swagger objects detailed above and in all JSDoc @swagger documention comments.

All swagger objects may contain the elements tags and components(except the ones specified in `config.routes.js) e.g.

{
  tags: [
    {
      name: 'Test Module',
      description: 'Module description ...',
      externalDocs: { url: 'https://docs.com/test' }
    }
  ],
  components: {
    schemas: {
      test: { ... }
    }
  }
}

Similarly, JSDoc @swagger tags may define tags and components:

/**
 * @swagger
 *
 * tags:
 *   - name: Test Module
 *     description: |
 *       Module description
 *       (continued).
 *
 *       Another paragraph.
 *
 *     externalDocs:
 *       url: https://docs.com/test
 *       description: Refer to these docs
 *
 * components:
 *   schemas:
 *     test:
 *       ...
 */

Tags Handling

Tags are added to the top-level Swagger/OpenAPI definitions as follows:

  1. If a tags with the specified name does not exist, it is added.
  2. Where a tag with the specified name does exist, elements of that tag that do not exist are added e.g. description and externalDocs elements.

Note that a final clean-up phase is run after processing, which performs the following:

  1. Removal of unreferenced tags; and
  2. Creation of tags referenced but are not defined.

Component Element Handling

Elements of components are added to the top-level Swagger/OpenAPI definitions as follows:

  1. Elements of the component definition reference (schemas, parameters, etc) are added where they do not exist.
  2. Existing elements are not overwritten or merged.

For example, the element components.schemas.pet will be added as part of a merge process, but the contents of multiple definitions of pet will not be merged.

The following elements (from the OpenAPI 3 specification) are handled:

let componentDefinitionReference = {
    // Reusable schemas (data models)
    schemas: {},
    // Reusable path, query, header and cookie parameters
    parameters: {},
    // Security scheme definitions (see Authentication)
    securitySchemes: {},
    // Reusable request bodies
    requestBodies: {},
    // Reusable responses, such as 401 Unauthorized or 400 Bad Request
    responses: {},
    // Reusable response headers
    headers: {},
    // Reusable examples
    examples: {},
    // Reusable links
    links: {},
    // Reusable callbacks
    callbacks: {},
};

Advanced Filtering/Processing of Generated Swagger

Three mechanisms are provided to enable advancing filtering of the Swagger generation process:

  1. An includeRoute() function used to filter routes to be included in generated Swagger output.
  2. An updateBlueprintActionTemplates() function allows customisation of the templates used to generate Swagger for blueprints.
  3. A postProcess() function allows an alternate mechanism for saving and/or modification of the generated Swagger output before it is written to the output file.

Each is configured in config/swaggergenerator.js.

Route Information

This hook parses all routes, custom and blueprint, before commencing the generation of the Swagger output. Each route is described by a SwaggerRouteInfo object (see defintion here):

export interface SwaggerRouteInfo {
  middlewareType: MiddlewareType; //< one of action|blueprint

  verb: HTTPMethodVerb; //< one of all|get|post|put|patch|delete
  path: string; //< full Sails URL as per sails.getUrlFor() including prefix
  variables: string[]; //< list of ALL variables extracted from path e.g. `/pet/:id` --> `id`
  optionalVariables: string[]; //< list of optional variables from path e.g. `/pet/:id?`

  action: string; //< either blueprint action (e.g. 'find') or action identity (e.g. 'subdir/reporting/run')
  actionType: ActionType; //< one of blueprint|shortcutBlueprint|controller|standalone|actions2|function
  actions2Machine?: Sails.Actions2Machine; //< for actionType === 'actions2', details of the action2 machine

  model?: SwaggerSailsModel; //< reference to Sails Model (blueprints only)
  associationAliases?: string[]; //< association attribute names (relevant blueprint routes only)

  defaultTagName?: string; //< default tag name for route, if any, based on Sails Model or Controller

  swagger?: SwaggerActionAttribute; //< per-route Swagger (OpenApi Operation)
}

Other interfaces for models, swagger elements etc may be found in interfaces.ts.

Route Filtering

The includeRoute(routeInfo): boolean function may be used to select which routes are included in the generated Swagger output.

For example:

module.exports['swagger-generator'] = {
  includeRoute: (routeInfo) => {
    let c = routeInfo.controller;
    if(!c) return true;
    if(c.toLowerCase().startsWith('user')) return true;
    return false;
  }
}

Customising Blueprint Action Templates

The templates used for generating Swagger for each Sails blueprint action route may be customised / modified / added to using the updateBlueprintActionTemplates config option e.g. to support custom blueprint actions/routes.

For example:

module.exports['swagger-generator'] = {
  updateBlueprintActionTemplates: function(blueprintActionTemplates) {
    blueprintActionTemplates.search = { ... };
    return blueprintActionTemplates;
  }
}

The blueprintActionTemplates object contains keys of the blueprint action names and values as per the following example (refer to the source code for the default templates):

let blueprintActionTemplates = {
  findone: {
    summary: 'Get {globalId} (find one)',
    description: 'Look up the **{globalId}** record with the specified ID.',
    externalDocs: {
      url: 'https://sailsjs.com/documentation/reference/blueprint-api/find-one',
      description: 'See https://sailsjs.com/documentation/reference/blueprint-api/find-one'
    },
    parameters: [
      'primaryKeyPathParameter', // special case; filtered and substituted during generation phase
      { $ref: '#/components/parameters/LimitQueryParam' },
    ],
    resultDescription: 'Responds with a single **{globalId}** record as a JSON dictionary',
    notFoundDescription: 'Response denoting **{globalId}** record with specified ID **NOT** found',
    // if functions, each called with (blueprintActionTemplate, routeInfo, pathEntry)
    modifiers: ['addSelectQueryParam', exampleModifierFunctionRef],
  },
  ...
};

Note that:

  1. For summary and description strings the value {globalId} is replaced with the applicable Sails model value.
  2. Parameters values are Swagger definitions, with the exception of the special string value primaryKeyPathParameter, which may be used to include a reference to a model's primary key.
  3. Modifiers are used to apply custom changes to the generated Swagger, noting that:
    • String values are predefined in generatePaths() (refer to the source code); valid modifiers are:
      • addPopulateQueryParam
      • addSelectQueryParam
      • addOmitQueryParam
      • addModelBodyParam
      • addModelBodyParamUpdate
      • addResultOfArrayOfModels
      • addAssociationPathParam
      • addAssociationFKPathParam
      • addAssociationResultOfArray
      • addResultOfModel
      • addResultNotFound
      • addResultValidationError
      • addFksBodyParam
      • addShortCutBlueprintRouteNote
    • Functions are called as func(blueprintActionTemplate, routeInfo, pathEntry, tags, components) where
      • blueprintActionTemplate the blueprint action template (see above) to which the modifier relates
      • routeInfo the route information object (see above) for which the Swagger is being generated
      • pathEntry the generated Swagger path entry to be modified
      • tags the generated Swagger tag definitions to be modified/extended
      • components the generated Swagger component definitions to be modified/extended

Post-processing Generated Swagger Output

The final generated Swagger output may be post-processed before it is written to the output file using a post-processing function specified as the postProcess config option.

For situations where saving the generated swagger documentation JSON to a file is not desired/appropriate, the postProcess config option may be used to specify an alternate save mechanism.

Note that if swaggerJsonPath config option is empty/null/undefined the output file will not be written.

For example:

module.exports['swagger-generator'] = {
  postProcess: function(specifications) {
    let sch = specifications.components.schemas;
    Object.keys(sch).map(k => {
      sch[k].description = sck[k].description.toUpperCase();
    });
  }
}

Testing

  • Clone this repository

  • Install all development dependencies

 npm install
  • Then run test
npm test

Contribute

Fork this repo and push in your ideas. Do not forget to add a bit of test(s) of what value you adding.

  • stick to conventional commit message here or read more angular commit pattern
  • While developing, you can run the below command to start nodemon watch too run linting and testing on .ts changes
npm run dev

Changelog

See the different releases here

License

MIT License (MIT)

sails-hook-swagger-generator's People

Contributors

alexandreloub avatar anasuya1117 avatar aristona avatar danielsharvey avatar dependabot[bot] avatar eonyenezido avatar theoomoregbee 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

sails-hook-swagger-generator's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npmPublish option.

The npmPublish option option, if defined, must be a Boolean.

Your configuration for the npmPublish option is false.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Swagger reads unrelated information

Hi,

This is how my Swagger UI looks like.

image

My route:

image

My controller:

image

Why Swagger reads the property ID, and why does it read "body" object twice? Am I doing something wrong?

Ps. Token is coming from policies, but there is nothing related to ID in the policies.

Customization of blueprint routes on model does not work

I'm not able to customize the blueprint route documentation: Neither by adding swagger JSDoc nor by adding the swagger object to the model (api/models/Foo.js):

/**
 *  @swagger
 *
 * /find:
 *    summary: Foo
 *    description: Bar
 */
swagger: {
    actions: {
      find: {
        summary: 'Foo',
        description: 'Bar',
      },
    },
  },

I dug into your code and found the referenced line. It's the line, where the paths get generated. The merged models contain the correct documentation (summary: 'Foo', description: 'Bar') but the models are not used in the generatePaths() function to override the blueprint templates. Did I overlook something or is this feature not implemented yet?

defaults(specifications.paths, generatePaths(routes, blueprintActionTemplates, theDefaults, specifications, models));

Tags not generated when using standalone actions

I am using standalone actions in my project as it is quite large and controller files do not cut it for me.

However when I use this hook to generate swagger.json I get the below error for my routes;

No tag for this identity ''

I then cannot see any tags on my routes and the generated swagger.json just lists all my routes.

I have looked at your implementation and you seem to be trying to match tags to controller identities. For cases like mine that use standalone actions can you pretty please provide an override so we can configure tags directly in the route if necessary?

Something like the below;

  // Block and unblock a user account
  'PUT /api/v1/admin/block-user/:userId': { 
    action: 'admin/users/block-user-with-id',
    swagger: {
      summary: 'Block/Unblock a user\'s account',
      description: 'This is to enable an admin block or unblock a user',
      body: {    
        action: { type: 'string', description: '"block" to block and "unblock" to unblock' },
      },
      tags: [{name: 'Admin'}]
    }
  },

Thanks!!!

Not able to run sails lift if I install this module

This is the error I am getting if I try sails lift after installing this mod. Please note that the app lifts normally when the hook is not installed


 info: Starting app...

 info: Initializing project hook... (`api/hooks/custom/`)
 info: Initializing `apianalytics` hook...  (requests to monitored routes will be logged!)
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity ''
No tag for this identity 'undefined.users'
No tag for this identity 'undefined.users'
No tag for this identity 'undefined.users'
No tag for this identity 'undefined.users'
No tag for this identity 'undefined.bookedservices'
No tag for this identity 'undefined.bookedservices'
No tag for this identity 'undefined.bookedservices'
No tag for this identity 'undefined.credits'
No tag for this identity 'undefined.studios'
No tag for this identity 'undefined.studios'
No tag for this identity 'undefined.studios'
No tag for this identity 'undefined.studios'
No tag for this identity 'undefined.studios'
No tag for this identity 'undefined.services'
No tag for this identity 'undefined.timings'
No tag for this identity 'undefined.timings'
No tag for this identity 'undefined.timings'
error: A hook (`custom`) failed to load!
error: 
error: TypeError: _.contains is not a function
    at Hook.initialize (/home/vikranth/Desktop/Happyfitt-Backend/api/hooks/custom/index.js:36:15)
    at Hook.wrapper [as initialize] (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/@sailshq/lodash/lib/index.js:3275:19)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/hooks/index.js:108:30
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:421:16
    at processQueue (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1565:20)
    at taskComplete (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1588:9)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1612:17
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:906:16
    at Hook.loadModules (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/hooks/index.js:178:14)
    at Hook.wrapper [as loadModules] (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/@sailshq/lodash/lib/index.js:3275:19)
    at modules (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/hooks/index.js:86:25)
    at runTask (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1621:13)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1559:13
    at processQueue (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1569:13)
    at Object.auto (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1555:5)
    at Hook.load (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/hooks/index.js:80:13)
    at Hook.wrapper [as load] (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/@sailshq/lodash/lib/index.js:3275:19)
    at loadHook (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/app/private/loadHooks.js:212:17)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/app/private/loadHooks.js:344:13
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:3083:16
    at eachOfArrayLike (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1003:9)
    at eachOf (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:1051:5)
    at Object.eachLimit (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:3145:5)
    at load (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/sails/lib/app/private/loadHooks.js:342:17)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:3853:24
    at replenish (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:946:17)
    at iterateeCallback (/home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:931:17)
    at /home/vikranth/Desktop/Happyfitt-Backend/node_modules/async/dist/async.js:906:16

error: Could not load Sails app.
error: 
error: Tips:
error:  • First, take a look at the error message above.
error:  • Make sure you've installed dependencies with `npm install`.
error:  • Check that this app was built for a compatible version of Sails.
error:  • Have a question or need help?  (http://sailsjs.com/support)

Cannot read property 'http_method' of undefined

I'm getting the following error when starting the generator with sails lift:
The ... stand for the full path (I don't want to share here).

A hook (`swagger-generator`) failed to load!
error: TypeError: Cannot read property 'http_method' of undefined
    at ...\node_modules\sails-hook-swagger-generator\lib\parsers.js:103:21
    at ...\node_modules\lodash\index.js:3073:15
    at baseForOwn (...\node_modules\lodash\index.js:2046:14)
    at ...\node_modules\lodash\index.js:3043:18
    at Function.<anonymous> (...\node_modules\lodash\index.js:3346:13)
    at Object._parseRoutes [as routes] (...\node_modules\sails-hook-swagger-generator\lib\parsers.js:67:7)
    at Object._generateRoutes [as routes] (...\node_modules\sails-hook-swagger-generator\lib\generators.js:149:26)
    at module.exports (...\node_modules\sails-hook-swagger-generator\lib\swaggerDoc.js:15:38)
    at Hook.initialize (...\node_modules\sails-hook-swagger-generator\index.js:39:13)
    at Hook.wrapper [as initialize] (...\node_modules\sails\node_modules\@sailshq\lodash\lib\index.js:3250:19)
    at ...\node_modules\sails\lib\hooks\index.js:88:16
    at ...\node_modules\sails\node_modules\async\lib\async.js:52:16
    at ...\node_modules\sails\node_modules\async\lib\async.js:548:17
    at ...\node_modules\sails\node_modules\async\lib\async.js:542:17
    at _arrayEach (...\node_modules\sails\node_modules\async\lib\async.js:85:13)
    at Immediate.taskComplete (...\node_modules\sails\node_modules\async\lib\async.js:541:13)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
    at processImmediate [as _immediateCallback] (timers.js:617:5)

Do you have any suggestions here?

Cannot find module 'lodash/assign'

After installing the module with npm I get this error. I could fix it by going into the node_modules folder of this package and running npm install. But on our CI system this trick does not work.

Is there something missing i have to to or is this an issue? If so, a proper fix would be appreciated.

This is the error log I get.

error: Failed to lift app: { Error: Cannot find module 'lodash/assign'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/circleci/repo/node_modules/sails-hook-swagger-generator/build/lib/generators.js:36:32)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/circleci/repo/node_modules/sails-hook-swagger-generator/build/lib/swagger-doc.js:51:20)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32) code: 'MODULE_NOT_FOUND' }

Customizing Responses

How can I customize responses? Change error codes, display custom error messages and show the structure of a returned object.

For now, all of my responses in Swagger UI look like this:
image

Custom Route Configuration - not working as expected

This is my route definition:

'POST /api/v1/projects/:project_id/assignments': {
    controller: 'AssignmentController',
    action: 'create',
    swagger: {
      summary: 'Creating a new Annotation Assignment',
      description: 'Create a new annotation assignment and assign tasks to annotators',
      body: {
        title: {
          type: 'string',
          required: true
        },
        description: {
          type: 'string',
          required: true
        },
        dataset_id: {
          type: 'string',
          required: true
        },
        sample_dataset: {
          type: 'string',
          required: true
        },
        annotators: {
          type: 'json',
          required: true
        }
      },
      parameters: [{
        in: 'path',
        name: 'project_id',
        required: true,
        type: 'integer',
        description: 'ID of the current project'
      }]
    }
  }

This is what I get in the Swagger UI:
image

swaggerGenerator.js is throwing error

include-all attempted to require(/home/anasuya/Documents/FrescoPlay/date-api/config/swaggergenerator.js), but an error occurred::
Details:ReferenceError: sails is not defined
at Object. (/home/anasuya/Documents/FrescoPlay/date-api/config/swaggergenerator.js:12:22)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/include-all/lib/help-include-all-sync.js:271:33
at Array.forEach ()
at _recursivelyIncludeAll (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/include-all/lib/help-include-all-sync.js:174:11)
at includeAll (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/include-all/lib/help-include-all-sync.js:292:5)
at helpBuildDictionary (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/include-all/lib/help-build-dictionary.js:43:15)
at Function.module.exports.aggregate (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/include-all/index.js:101:10)
at Array.loadOtherConfigFiles (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/lib/hooks/moduleloader/index.js:247:22)
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:591:38
at _arrayEach (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:85:13)
at Object.async.auto (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:552:9)
at Hook.loadUserConfig (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/lib/hooks/moduleloader/index.js:245:13)
at Hook.wrapper [as loadUserConfig] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/@sailshq/lodash/lib/index.js:3250:19)
at Hook.loadModules (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/lib/hooks/userconfig/index.js:41:27)
at Hook.wrapper [as loadModules] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/@sailshq/lodash/lib/index.js:3250:19)

Unwanted params

I have an 'id' path param, which is dot defined anywhere and I'd like it gone.

Also, all my requests have a 'token' header. I would like to remove it, since I am using a specific Authorization header.

Here is my route definition:

'DELETE /api/v1/projects/:project_id' : {
    controller: 'ProjectController',
    action: 'destroy',
    swagger: {
      summary: 'Delete',
      description: 'Delete a project and all its dependents',
      parameters: [
        {
          in: 'header',
          name: 'Authorization',
          required: true,
          type: 'string',
          description: 'Bearer {{token}}'
        },
        {
          in: 'path',
          name: 'project_id',
          required: true,
          type: 'integer',
          description: 'ID of the project to delete'
        }
      ],
    }
  }

The Swagger UI output:
image

Not generating routes from controller correctly

Hi I get something along the lines of

No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'
No tag for this identity 'v1/vdc'

When I sails lift. These are related to the functions in my controller. Is there anyway to have the swagger document generated without having to directly specify the routes again in config.routes.js

like so

'get /v1/vdc/provisionNew': {
  controller: 'v1/vdcController',
  action: 'provisionNew',
  swagger: {
    summary: 'ProvisionNew',
    description: 'This is for authentication of any user',
    body: {
      username: { type: 'string', required: true },
      password: { type: 'password', required: true }
    },
    query: [{ $ref: '#/parameters/IDPathParam' }]
  }
}

It would be better if it could autogenerate from the controller without having to redo the routes.

Defining Arrays as body or formData params

I couldn't find a way to define array-type params through the custom routes.

When a param in the body is defined as string, it is possible to send it as a string array, but the type in the UI says 'string' - Which clearly defeats the point of having a swagger UI...

Can you please provide a tested, working example of a custom route which requires an array as a body param?

Generate second swagger.config

Hi Team,

I trying to create other swagger.config file for some selected routes but I know that I have the same routes.js file for this so how can handle this for separate two types of different swagger.json

Sails lift is giving TypeError: Cannot read property 'http_method' of undefined on v2.3.0

error: A hook (swagger-generator) failed to load!
verbose: Lowering sails...
verbose: Sent kill signal to child process (5876)...
verbose: Shutting down HTTP server...
verbose: HTTP server shut down successfully.
error: TypeError: Cannot read property 'http_method' of undefined
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/parsers.js:103:22
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:3073:15
at baseForOwn (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:2046:14)
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:3043:18
at Function. (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:3346:13)
at Object._parseRoutes [as routes] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/parsers.js:67:7)
at Object._generateRoutes [as routes] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/generators.js:149:26)
at module.exports (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/swaggerDoc.js:15:38)
at Hook.initialize (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/index.js:44:13)
at Hook.wrapper [as initialize] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/@sailshq/lodash/lib/index.js:3250:19)
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/lib/hooks/index.js:88:16
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:52:16
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:548:17
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:542:17
at _arrayEach (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:85:13)
at Immediate.taskComplete (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails/node_modules/async/lib/async.js:541:13)
at runCallback (timers.js:800:20)
at tryOnImmediate (timers.js:762:5)
at processImmediate [as _immediateCallback] (timers.js:733:5)

remove auto generated routes

i'm using sails 0.12 /1.0
when i configure hook it generate all methods of controller in .json file ,
but i want only those routes which is in my congig/route.js file

Actions 2 documentation not generating

Hello,

First, thanks for this great/handy project.

Ran into an issue. It seems Action 2 documentation is not being generated. I've used the same subdir/actions2.js file as you have in this repo and created a route on my config/routes.js

'get /actions2': 'subdir/actions2'

Screen Shot 2020-05-16 at 10 32 02 PM

However, the generated json in swagger.json still has default values.

Screen Shot 2020-05-16 at 10 34 18 PM

Thanks, any help would be appreciated.

Not interpreting parameters right way

I have a route like this
get /projects/:id/articles

In the generated swagger documentation it reads like this
GET /projects/{id/articles}

I would expect it to be
GET /projects/{id}/articles}

Using sails 1.0.0, generator version 2.6.0

swaggergenerator.js override not working

I'm using sails 0.12.13

All is working good expect I can't override the specifications. Doing some digging I found that the problem is that in lib/swaggerDoc.js, the context.configKey is swagger-generator, and not swaggergenerator. So instead of module.exports.swaggergenerator I had to module.exports["swagger-generator"] to make it work.

restPrefix not used

When I set rest:true and create a custom restPrefix like restPrefix: '/api/v1', rest route are not generate with prefix.
I don't want to change basePath in config/swaggergenerator.js. My app have some custom route with different prefix.

Not defined Models

Hello.
I have a problem with model definitions. I use sequelize.
What should I do to make the data for the model (#/definitions/{{modelName}}) pull up from the model itself? Because now it is empty.

image of swagger model

Model example:

module.exports = function (sequelize, DataTypes) {
  var activities = sequelize.define("activities", {
    removed: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: false
    },
    createdAt: {
      type: DataTypes.DATE
    },
    updatedAt: {
      type: DataTypes.DATE
    },
    agencyId: {
      type: DataTypes.INTEGER,
      references: {
        model: "companies",
        key: "id"
      }
    }
  });
  return activities;
};

I would be grateful for any help.

Error on sails lift

Hi I get and error on sails lift

our routes { '/csrfToken':
{ target: [Function: csrfToken],
cors: { origin: '-', credentials: true } },
'/': { view: 'homepage' } }
error: A hook (swagger-generator) failed to load!
error: TypeError: Cannot read property 'http_method' of undefined
at D:\Google Drive\Ignite Workspace\flow\node_modules\sails-hook-swagger-generator\lib\parsers.js:103:22
at D:\Google Drive\Ignite Workspace\flow\node_modules\lodash\index.js:3073:15
at baseForOwn (D:\Google Drive\Ignite Workspace\flow\node_modules\lodash\index.js:2046:14)
at D:\Google Drive\Ignite Workspace\flow\node_modules\lodash\index.js:3043:18
at Function. (D:\Google Drive\Ignite Workspace\flow\node_modules\lodash\index.js:3346:13)
at Object._parseRoutes [as routes] (D:\Google Drive\Ignite Workspace\flow\node_modules\sails-hook-swagger-generator\lib\parsers.js:67:7)
at Object._generateRoutes [as routes] (D:\Google Drive\Ignite Workspace\flow\node_modules\sails-hook-swagger-generator\lib\generators.js:149:26)
at module.exports (D:\Google Drive\Ignite Workspace\flow\node_modules\sails-hook-swagger-generator\lib\swaggerDoc.js:15:38)
at Hook.initialize (D:\Google Drive\Ignite Workspace\flow\node_modules\sails-hook-swagger-generator\index.js:44:13)
at Hook.wrapper [as initialize] (D:\Google Drive\Ignite Workspace\flow\node_modules@sailshq\lodash\lib\index.js:3250:19)
at D:\Google Drive\Ignite Workspace\flow\node_modules\sails\lib\hooks\index.js:88:16
at D:\Google Drive\Ignite Workspace\flow\node_modules\sails\node_modules\async\lib\async.js:52:16
at D:\Google Drive\Ignite Workspace\flow\node_modules\sails\node_modules\async\lib\async.js:548:17
at D:\Google Drive\Ignite Workspace\flow\node_modules\sails\node_modules\async\lib\async.js:542:17
at _arrayEach (D:\Google Drive\Ignite Workspace\flow\node_modules\sails\node_modules\async\lib\async.js:85:13)
at Immediate.taskComplete [as _onImmediate] (D:\Google Drive\Ignite Workspace\flow\node_modules\sails\node_modules\async\lib\async.js:541:13)
at runCallback (timers.js:789:20)
at tryOnImmediate (timers.js:751:5)
at processImmediate [as _immediateCallback] (timers.js:722:5)

Getting error on sails lift

A hook (swagger-generator) failed to load!
error: TypeError: Cannot read property 'trim' of undefined
at /home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/parsers.js:77:39
at baseFor (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:2007:13)
at baseForOwn (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:2061:14)
at baseEach (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:1820:16)
at Function.forEach (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/lodash/index.js:5953:11)
at Object._parseRoutes [as routes] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/parsers.js:56:7)
at Object._generateRoutes [as routes] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/generators.js:149:26)
at module.exports (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/lib/swaggerDoc.js:15:38)
at Hook.initialize (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/sails-hook-swagger-generator/index.js:39:13)
at Hook.wrapper [as initialize] (/home/anasuya/Documents/FrescoPlay/date-api/node_modules/@sailshq/lodash/lib/index.js:3250:19)

Improper routes handling

When I'm having routes configured e.g.:

'get /user/:id/creditCards': {
    controller: 'user',
    action: 'get-or-create'
}

the generated json shows incorrectly

/user/{id/creditCards}

P.S. I'm using sailsjs 1.0

Custom header params

Hi,

I am trying to add custom header params like tokens but as per documentation it is not properly generated.

Is it possible to generate global params for all endpoint as token are doing without adding ref in all endpoints ?

Swagger UI

I'm able to generate the JSON file in the ./swagger folder. How do I integrate swagger UI along with it in a sails app on some path say /swagger-api/

How to set nested objects in "body" parameters?

I want to set necessary parameters in controller in routes.js.
I already tried different options, but without result.
I can set body parameters as describe here, but there is described option only with types that are not an objects (not nested). Attempting to use the "schema" also did not lead to success.

Could you help me understand how to properly use your library to achieve the results described above.

Example of my ajv schema of validation. I need structurally the same result in swagger as it.

    signup: {
      type: "object",
      properties: {
        company: {
          type: "object",
          properties: {
            name: {type: "string", minLength: 1, maxLength: 50},
            email: {type: "string", format: "email", minLength: 0, maxLength: 50}
          },
          required: ["name", "email"]
        },
        contact: {
          type: "object",
          properties: {
            firstName: {type: "string", minLength: 1, maxLength: 50},
            email: {type: "string", format: "email", minLength: 0, maxLength: 50}
          },
          required: ["firstName", "email"]
        }
      },
      required: ["company", "contact"]
    }

I would be grateful for any help!

swagger.json

How can i change the location of the generate swagger.json file?

Ignore Sails Blueprint routes.

I can't find a way to ignore sails blueprint routes. Blueprints are disabled in the blueprint config file but they still appear in the swagger.json. I tried sails-swagger and it does ignore the blue print routes but it has a whole slew of other problems. So I'm curious if there is a way to not include the blueprint routes in the swagger.json.

For example, I have POST /api/0.1/user in my route.js file. I get that in the swagger.json but then i also get sails POST /user.

Thanks for any help.

Custom action does not overwrite blueprint action documentation

My custom user/create.js action does not overwrite the blueprint action documentation.

I debugged your code and set the breakpoint at

mergeControllerSwaggerIntoRouteInfo(sails, routes, controllers, controllersJsDoc);

The action is listed in the controllers.actions attribute:

Object {actionType: "actions2", defaultTagName: "create", friendlyName: "Create", description: 
  "Create user.", inputs: Object,}
  swagger-doc.js:106
  actionType:"actions2"
  defaultTagName:"create"
  description:"Create user."
  exits:Object {passwordNotMatch: Object, emailNotMatch: Object, emailAlreadyInUse: Object,}
  fn:async function (inputs, exits) {  }
  friendlyName:"Create"
  globalId:"user/create.js"
  identity:"user/create.js"
  inputs:Object {first_name: Object, last_name: Object, email: Object,}

But in the routes variable it is defined as "BLUEPRINT" instead of "ACTION" and it contains no information about the custom user/create action:

Object {middlewareType: "BLUEPRINT", verb: "post", path: "/api/user", variables: Array(0), 
  optionalVariables: Array(0),}
  swagger-doc.js:106
  action:"create"
  actionType:"blueprint"
  associationAliases:Array(0) []
  middlewareType:"BLUEPRINT"
  model:Object {globalId: "User", primaryKey: "id", identity: "user",}
  optionalVariables:Array(0) []
  path:"/api/user"
  swagger:undefined
  variables:Array(0) []
  verb:"post"
}

Therefore the blueprint documentation is used in the result. It would be really great to use the integrated blueprint override functionality of sails. But, if this feature costs too much effort, I could also rename my action and add a custom route as a workaround.

Inconsistent Behaviour - Auto Generated

For eample, For two routes (not custom, but basic sails definition), I get two weirdly different results.
The routes in question are defined as such:

'DELETE /api/v1/projects/:project_id/assignments/:assignment_id': 'AssignmentController.destroy',
'DELETE /api/v1/projects/:project_id/members/:user_id': 'ProjectController.deleteMember',

The Swagger UI generated for the the first is (correct) :
image

And for the second (wrong):
image

Any idea why that happens and how to fix it?

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.