Code Monkey home page Code Monkey logo

sails-swagger's Introduction

sails-swagger

NPM version Build status Dependency Status Code Climate

swagger.io (v2.0) hook for Sails. The application's models, controllers, and routes are aggregated and transformed into a Swagger Document. Supports the Swagger 2.0 specification.

Install

$ npm install sails-swagger --save

Configuration

// config/swagger.js
module.exports.swagger = {
  /**
   * require() the package.json file for your Sails app.
   */
  pkg: require('../package'),
  ui: {
    url: 'http://swagger.balderdash.io'
  }
};

Usage

After installing and configuring swagger, you can find the docs output on the /swagger/doc route.

You may also specify additional swagger endpoints by specifying the swagger spec in config/routes.js

/**
 * Route Mappings
 * @file config/routes.js
 * (sails.config.routes)
 *
 * Your routes map URLs to views and controllers.
 */

module.exports.routes = {

    /***************************************************************************
     *                                                                          *
     * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
     * etc. depending on your default view engine) your home page.              *
     *                                                                          *
     * (Alternatively, remove this and add an `index.html` file in your         *
     * `assets` directory)                                                      *
     *                                                                          *
     ***************************************************************************/

    '/': {
        view: 'homepage'
    },

    /***************************************************************************
     *                                                                          *
     * Custom routes here...                                                    *
     *                                                                          *
     * If a request to a URL doesn't match any of the custom routes above, it   *
     * is matched against Sails route blueprints. See `config/blueprints.js`    *
     * for configuration options and examples.                                  *
     *                                                                          *
     ***************************************************************************/
    'get /groups/:id': {
        controller: 'GroupController',
        action: 'test',
        skipAssets: 'true',
        //swagger path object
        swagger: {
            methods: ['GET', 'POST'],
            summary: ' Get Groups ',
            description: 'Get Groups Description',
            produces: [
                'application/json'
            ],
            tags: [
                'Groups'
            ],
            responses: {
                '200': {
                    description: 'List of Groups',
                    schema: 'Group', // api/model/Group.js,
                    type: 'array'
                }
            },
            parameters: []

        }
    },
    'put /groups/:id': {
        controller: 'GroupController',
        action: 'test',
        skipAssets: 'true',
        //swagger path object
        swagger: {
            methods: ['PUT', 'POST'],
            summary: 'Update Groups ',
            description: 'Update Groups Description',
            produces: [
                'application/json'
            ],
            tags: [
                'Groups'
            ],
            responses: {
                '200': {
                    description: 'Updated Group',
                    schema: 'Group' // api/model/Group.js
                }
            },
            parameters: [
                'Group' // api/model/Group.js
            ]

        }
    }
};


License

MIT

Maintained By

sails-swagger's People

Contributors

alexisno avatar gggordon avatar moisesrodriguez avatar rwoverdijk avatar samuelmarks avatar tjwebb 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

sails-swagger's Issues

Sails-swagger generates useless/strange routes

With a simple account model swagger-sails generate stuff like:

DELETE /account/find/{id}
GET /account/find/{id}
PATCH /account/find/{id}
POST /account/find/{id}
PUT /account/find/{id}

Is it a normal behaviour?

Nested blueprint route returning an array of objects instead of one object when including an :id

GET /model1/:id/model2/:id returns an array of objects (same response as /model1/:id/model2/ (Not expected).
GET /model2/:id returns just one object as expected (Expected).

Model1 has a one to many relationship with Model2.

More specifically, I have 3 sails models with the following one to many relationships:

- User
  - Account
    - Transaction
    - Transaction...
  - Account ...

When I GET /users/:id/accounts/:id, I get an array like so

[
  {
    "user": "d7156354-6587-4614-b92b-7e8091e3311c",
    "id": "e7c41cc3-7b98-482e-8aa3-2cdd42eab3a1"
  }
]

I expected this to return a single Account object, and not an array containing just one Account object.

I get a single Account object as expected when I GET /accounts/:id
I also get a single User object as expected when I GET /users/:id/,

My model files look like so

// User.js
module.exports = {
  autoCreatedAt: false,
  autoUpdatedAt: false,
  attributes: {
    id: {
      type: 'string',
      unique: true,
      primaryKey: true,
      defaultsTo: () => uuid.v4(),
    },
    name: {
      type: 'string',
    },
    email: {
      type: 'string',
      unique: true,
    },
    accounts: {
      collection: 'account',
      via: 'user',
    }
  }
};
// Account.js
module.exports = {
  autoCreatedAt: false,
  autoUpdatedAt: false,
  attributes: {
    id: {
      type: 'string',
      unique: true,
      primaryKey: true,
      defaultsTo: () => uuid.v4(),
    },
    date: {
      type: 'date',
      defaultsTo: () => new Date(),
    },
    amount: {
      type: 'float',
      defaultsTo: 0.0,
    },
    account: {
      model: 'account',
    },
    type: {
      type: 'string',
      enum: ['credit', 'debit'],
      defaultsTo: 'credit',
    },
    description: {
      type: 'string',
      defaultsTo: () => `Transaction at ${new Date()}`
    }
  }
};
// Transaction.js
module.exports = {
  autoCreatedAt: false,
  autoUpdatedAt: false,
  attributes: {
    id: {
      type: 'string',
      unique: true,
      primaryKey: true,
      defaultsTo: () => uuid.v4(),
    },
    date: {
      type: 'date',
      defaultsTo: () => new Date(),
    },
    amount: {
      type: 'float',
      defaultsTo: 0.0,
    },
    account: {
      model: 'account',
    },
    type: {
      type: 'string',
      enum: ['credit', 'debit'],
      defaultsTo: 'credit',
    },
    description: {
      type: 'string',
      defaultsTo: () => `Transaction at ${new Date()}`
    }
  }
};

Am I doing it wrong?

Way to customize json output

Hi guys

I'd like to know about how do you customize your output.

Let's say you want to return a 400 or 403, or if you want to return a custom model which is not persist in database or also how do you define query parameters ?

How do you deal with that and have you ever think about adding some more customization. If no, I'll be glad to help

Thank you

Default Models (contact and group) - primary key association issue

  1. I've installed sails-swagger and swagger-ui.
  2. When I do sails lift I get an error - Trying to create an association on a model that doesn't have a Primary Key.
  3. This error is due to the default models (contact and group) that are part of sails-swagger package under dist/api/models
  4. These 2 models do not have a primary key specified and hence the above error. If I edit the above models and include a primary key it works with out any issue and i am able to view the documentation.
  5. Editing the models in the package is not an option, so i do i get around this issue

TypeError: Cannot read property 'pkg' of undefined

When trying to run my simple Sails.JS app (with swaggerui included), I'm getting the following error:

$ sails lift

info: Starting app...

debug: hookPath: DummyPath\Software\MyService\node_modules\sails-swagger\dist\api\hooks\swagger
debug: marlinspike (swagger): loading config from DummyPath\Software\MyService\node_modules\sails-swagger\dist\config
debug: marlinspike (swagger): loading Services from DummyPath\Software\MyService\node_modules\sails-swagger\dist\api\services...
warn: marlinspike (swagger): no Services found. skipping
debug: marlinspike (swagger): loading Models...
debug: marlinspike (swagger): loading Controllers...
debug: marlinspike (swagger): loading Policies...
warn: marlinspike (swagger): no Policies found. skipping
DummyPath\Software\MyService\node_modules\sails-swagger\dist\api\hooks\swagger\index.js:49
        hook.doc = _libXfmr2['default'].getSwagger(_this.sails, _this.sails.config.swagger.pkg);
                                                                                          ^

TypeError: Cannot read property 'pkg' of undefined
    at DummyPath\Software\MyService\node_modules\sails-swagger\dist\api\hooks\swagger\index.js:49:91
    at DummyPath\Software\MyService\node_modules\sails\lib\app\private\after.js:91:14
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:721:13
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:52:16
    at done (DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:246:17)
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:44:16
    at Sails.<anonymous> (DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:718:17)
    at Sails.<anonymous> (DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:167:37)
    at Object.onceWrapper (events.js:293:19)
    at emitNone (events.js:86:13)
    at Sails.emit (events.js:188:7)
    at Sails.emitter.emit (DummyPath\Software\MyService\node_modules\sails\lib\app\private\after.js:50:11)
    at sailsReady (DummyPath\Software\MyService\node_modules\sails\lib\app\lift.js:53:11)
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:721:13
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:52:16
    at DummyPath\Software\MyService\node_modules\sails\node_modules\async\lib\async.js:269:32

npm install, npm uninstall sails or npm cache clear doesn't work.
I've already tried to reinstall grunt-cli as well and sails-swagger again...
Does anyone have a solution here?

Latest master is breaking

Any reason why the latest sails-swagger master is throwing an error even after successful npm install.

error: Error: Cannot find module '/Users/a/node_modules/sails-swagger'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)

/swagger/doc not using global CORS settings

My current settings for CORS are:

allRoutes: true
origin: '*'
methods: 'GET, POST, PUT, DELETE, OPTIONS'

When accessing the /swagger/doc route (with the default config) I don't get my CORS headers.
Just these:

Connection:keep-alive
Date:Thu, 17 Dec 2015 22:56:49 GMT
ETag:W/"f1f7-1299879629"
X-Powered-By:Sails <sailsjs.org>

But my other routes have the CORS headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://someothersite.com
Access-Control-Expose-Headers:
Connection:keep-alive
Content-Length:10887
Content-Type:text/html; charset=utf-8
Date:Thu, 17 Dec 2015 22:46:49 GMT
ETag:W/"2a87-3377312003"
X-Powered-By:Sails <sailsjs.org>

Outdated sails-swagger npm package

I've been trying to set my custom routes swagger options but it seems the npm package is outdated because there's also a CORS related bug on it (already solved on this repository).

It would be great if you generate the npm package with the last version.

Cannot set property 'doc' of undefined

When i use sails-swagger it says :- error: The bootstrap function threw an error after its callback was called :: Ty peError: Cannot set property 'doc' of undefined. Do you have any documentation about how to implement.

I dig more into code and found
this.sails.hooks.swagger get undefined
in node_modules\sails-swagger\dist\api\hooks\swagger\index.js

Query parameters?

I have added custom route with query parameters in the following way:

'get /query|limit': 'QueryController.find'

S.t. 'limit' is a query parameter.
This is according to sails docs.

However the generated json doesn't take it into account...
Is this feature not implemented?

it trows an error on startup

The bootstrap function threw an error after its callback was called :: TypeError: Invalid attempt to destructure non-iterable instance
    at server-location\node_modules\sails-swagger\dist\lib\xfmr.js:7:586
    at Object.getControllerFromRoute (server-location\node_modules\sails-swagger\dist\lib\xfmr.js:208:29)
    at Object.getPathTags (server-location\node_modules\sails-swagger\dist\lib\xfmr.js:178:183)
    at Object.getOperation (server-location\node_modules\sails-swagger\dist\lib\xfmr.js:169:25)
    at server-location\node_modules\sails-swagger\dist\lib\xfmr.js:155:26
    at server-location\node_modules\lodash\index.js:3395:24
    at server-location\node_modules\lodash\index.js:3073:15
    at baseForOwn (server-location\node_modules\lodash\index.js:2046:14)
    at Function.mapValues (server-location\node_modules\lodash\index.js:3394:9)
    at Object.getPathItem (server-location\node_modules\sails-swagger\dist\lib\xfmr.js:154:32)
    at server-location\node_modules\sails-swagger\dist\lib\xfmr.js:113:26
    at server-location\node_modules\lodash\index.js:3395:24
    at server-location\node_modules\lodash\index.js:3073:15
    at baseForOwn (server-location\node_modules\lodash\index.js:2046:14)
    at Function.mapValues (server-location\node_modules\lodash\index.js:3394:9)
    at Object.getPaths (server-location\node_modules\sails-swagger\dist\lib\xfmr.js:112:32) [TypeError: Invalid attempt to destructure non-iterable instance]

What I'm doing wrong?

Swagger UI integration

Hi,

I'm having the following errors when rendering swagger-ui :

screen shot 2017-03-25 at 12 56 46

I've copied the contents of the dist folder from swagger-ui under assets/docs but can't get it to work.

Thanks

integrating Swagger with existing sails project

Hi ,
I have an existing Sails app and I want to generate the API documentation dynamically.Tried writing the details, summery etc. parameters in the route.js of my sails app ,but it is not coming up in /swagger/doc
'/api/commonQuestions': { controller:'CommonQController', action:'index', swagger:{ method: [ 'GET' ], summary: 'gets Common Qs', description:'common questions 11', produces:'application/json', tags: [ 'common Questions' ], responses: { '201': { description: 'Product created', schema: 'user' //model } }/*, parameters: [ 'products' ]*/ } },

How to test controllers which are written in tyescript ??

I have followed all the steps mentioned by you to integrate sails js with swagger.
But while doing testing I am getting error.
In our project we have written the api controllers in tyescript.
Then we have written gulp code for converting it into javascript files.
But while testing those controllers using mocha, test is getting failed.

api/controllers/UserDetailsController.ts

import dbUtilies = require('../services/dbUtils');

// Get Users
export function get_users(req:any, res:any, next: Function):any {
  let name = req.query['name'];
  let id = req.query['id'];
  if (name) {
    let reqObj = {username: name};
    dbUtilies.getOne('user_details', reqObj).subscribe(
      data => {
        res.status(200).send(data);
      },
      err => {
        res.status(404).send(err);
      }
    );
  } else if (id) {
    let reqObj = {id: id};
    dbUtilies.getOne('user_details', reqObj).subscribe(
      data => {
        res.status(200).send(data);
      },
      err => {
        res.notFound(err);
        // res.status(404).send(err);
      }
    );
  } else {
    dbUtilies.getAll('user_details')
      .subscribe(
        data => {
          res.status(200).send(data);
        },
        err => {
          res.status(500).send(err);
        }
    );
  }
}
}

service in typescript

api/services/dbUtils.ts

import Rxjs = require('rxjs');
import sails = require('sails');

export function getAll(modelName: string) {
    console.log(modelName);
    return Rxjs.Observable.fromPromise(sails.models[modelName].find());
}

export function getOne(modelName: string, obj: any) {
    return Rxjs.Observable.fromPromise(sails.models[modelName].find(obj))
        .mergeMap(data => responseValidation(data));
}

export function create(modelName: string, obj: any) {
    return Rxjs.Observable.fromPromise(sails.models[modelName].create(obj));
}

export function update(modelName: string, obj: any, reqBody: any) {
    return Rxjs.Observable.fromPromise(sails.models[modelName].update(obj, reqBody))
        .mergeMap(data => responseValidation(data));
}

export function destroy(modelName: string, obj: any) {
    return Rxjs.Observable.fromPromise(sails.models[modelName].destroy(obj))
        .mergeMap(data => responseValidation(data));
}

function responseValidation(res: any) {
    if (res['length'] > 0) {
        return Rxjs.Observable.from(res);
    } else {
        return Rxjs.Observable.throw('No Data Found From The Given Object');
    }
}

test cases:

var supertest = require('supertest');
var assert = require('assert');

require('../../bootstrap.test');

describe('The UserDetailsController', function () {
    /* test for login */
    it('should get all users', function (done) {
        var agent = supertest.agent(sails.hooks.http.app);
        agent
            .get('/users')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200)
            .end(function (err, result) {
                if (err) {
                    done(err);
                } else {
                    result.body.should.be.an('array');
                    done();
                }
            });
    });

the error I am getting is:

Uncaught `include-all` attempted to `require(/Users/user/geocloud/sails-swagger-poc/api-platform/api/services/dbUtils.ts)`, but an error occurred:: 
Details:/Users/user/geocloud/sails-swagger-poc/api-platform/api/services/dbUtils.ts:1
(function (exports, require, module, __filename, __dirname) { import Rxjs = require('rxjs');
                                                              ^^^^^^
SyntaxError: Unexpected token import

Installation

after I make
npm install sails-swagger --save
and restart sails (I get verbose: swagger hook loaded successfully.)

All what I get is just huge swagger json. It's right? How can I get UI for it?
Also I get some strange models that I do not use - contact and group and association for it - contact_contacts_contact__group_contacts

Request/Response not served from SailJS because of CORS issue

I am running Web REST API on Swagger, Sail JS, when I am trying to access through Angular UI,. I have set the required headers in the UI and as well as enabled in sailjs > config/cors.js file with below values.

allRoutes: true,
origin: '*',
credentials: true,

From the UI application, I am setting below headers before sending any request.
this.headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'q=0.8;application/json;q=0.9' });
this.headers.set('Access-Control-Allow-Origin' , '*');
this.headers.set('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
this.headers.set('Access-Control-Allow-Headers', 'origin, content-type, accept');
this.headers.append('Access-Control-Allow-Credentials', 'true');
this.headers.append('Access-Control-Max-Age' , '86400');

But I am not able to get the response from Sail JS, can you please let me know if I am missing anything or do I need enable any other settings on the SailJS config.

Please do the needful to resolve this issue.

Error on Server startup

I've integrated sails-swagger like it's mentioned in the Read me file. I'm getting the following error:

debug: hookPath: /Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/hooks/swagger
debug: marlinspike (swagger): loading config from /Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/config
debug: marlinspike (swagger): loading Services from /Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/services...
info: Error: ENOENT: no such file or directory, scandir '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/services'
    at Error (native)
    at Object.fs.readdirSync (fs.js:813:18)
    at requireAll (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/node_modules/require-all/index.js:12:18)
    at Swagger.loadServices (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/dist/marlinspike.js:129:52)
    at Hook.configure (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/dist/marlinspike.js:198:51)
    at Hook.bound [as configure] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /usr/local/lib/node_modules/sails/lib/app/private/loadHooks.js:176:18
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:122:13
    at _each (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:121:9)
    at Object.async.series.configure (/usr/local/lib/node_modules/sails/lib/app/private/loadHooks.js:174:17)
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:620:25
    at iterate (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:157:25
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:626:21
    at done (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:132:19) { [Error: ENOENT: no such file or directory, scandir '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/services']
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/services' }
warn: marlinspike (swagger): no Services found. skipping
debug: marlinspike (swagger): loading Controllers...
debug: marlinspike (swagger): loading Policies...
info: Error: ENOENT: no such file or directory, scandir '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/policies'
    at Error (native)
    at Object.fs.readdirSync (fs.js:813:18)
    at requireAll (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/node_modules/require-all/index.js:12:18)
    at Swagger.loadPolicies (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/dist/marlinspike.js:93:52)
    at Hook.configure (/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/node_modules/marlinspike/dist/marlinspike.js:201:51)
    at Hook.bound [as configure] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /usr/local/lib/node_modules/sails/lib/app/private/loadHooks.js:176:18
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:122:13
    at _each (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:121:9)
    at Object.async.series.configure (/usr/local/lib/node_modules/sails/lib/app/private/loadHooks.js:174:17)
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:620:25
    at iterate (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:157:25
    at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:626:21
    at done (/usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:132:19) { [Error: ENOENT: no such file or directory, scandir '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/policies']
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/Users/varunachar/Work/learn/sample-sails/node_modules/sails-swagger/dist/api/policies' }
warn: marlinspike (swagger): no Policies found. skipping

I checked the node modules directory and the only folders that exist inside the dist folder are:

api/
|_ controllers/
|_ ..files
|_ hooks/
|swagger/
|
..files
|_ models/
config/
|_ ..files
lib/
|_ ..files

Can I omit routes/controllers and models not created in my server?

Currently I see there are Models that aren't present in my server like Group and Contact.
The controllers are missing in 0.5.1, but that's not the point.
I don't want to see those models and controllers, they should be just for testing purposes.
Could you please assist somehow?

Swagger shows many false operations

I have /tag/find... routes even though I didn't declare them.

Example TagController:

module.exports = {
    find: function(req, res, next) {
        validateFindRequest(req)
            .then(TagService.getTags)
            .then(function(results) {
                return res.json(results);
            })
            .catch(function(err) {
                return res.serverError(err);
            });
    }
};

All blueprints are off, I have this route:

'get /tag': 'TagController.find'

Result:
swagger_fixed_cropped

Sails version 0.12.x, module version 0.5.x.

Closed:
Apparently actions blueprint is true by default, I had to explicitly set it to false and now it works.

Roadmap: Ending Sails.js support. Migrating sails-swagger to Trails

In Q1 of 2016, sails-swagger will be migrated to run on the trails.js framework: https://github.com/trailsjs/trails. As many of you know, this project has been hamstrung by the Sails.js team's inability to release any of the 0.12.x series versions in a timely manner.

There is a long history behind the decision to migrate to Trails.js, some of which is documented in this thread in the Sails project: balderdashy/sails#3429 (comment). Unfortunately, because the Sails.js team is splintering and is no longer actively maintained, support for sails-swagger will cease in February 2016, and all new development on this module will occur here: https://github.com/trailsjs/trailpack-swagger.

Here is the ROADMAP for trails.js: https://github.com/trailsjs/trails/blob/master/ROADMAP.md

Query Parameters Missing

The parameter field is not being generated, is this a normal thing or i need to use the costume routes to generate them so i can use swagger ui to test my models?

Hook not triggered on sails 0.10.2

HI,
I've installed sails-swagger and setup a config/swagger.js file but when I lift the app, it seems there is nothing done (no output in the standard output).
I am missing something ?

Can't read json

After integrating sails-swagger. I can see the swagger url working but the error I am facing is "Can't read json from 'http://localhost:1337/docs'".
I want to know from where the list of API JSON is taken in swagger.

Can anyone help me in this? I am new in sails-swagger.

custom parameters are missing

With the current version of the npm package 0.51.0, the generated doc doesn't include the parameters specified for the routes.

['get /groups']: {
                    controller: 'authController',
                    action: 'login',
                    skipAssets: 'true',
                    //swagger path object
                    swagger: {
                        methods: ['GET'],

                        summary: ' Get Groups ',
                        description: 'Get Groups Description',
                        produces: [
                            'application/json'
                        ],
                        tags: [
                            'Groups'
                        ],
                        responses: {
                            '200': {
                                description: 'List of Groups',
                                schema: 'Group', //model,
                                type: 'array'
                            }
                        },
                        parameters: [{
                            "name": "id",
                            "in": "path",
                            "description": "ID of pet to use",
                            "required": true,
                            "type": "array",
                            "items": {
                                "type": "string"
                            },
                            "collectionFormat": "csv"
                        }, {
                            "name": "name",
                            "in": "query",
                            "description": "ID of pet to use",
                            "required": true,
                            "type": "string"
                        }, 'Contact']

                    }
                }

and the generated doc as below

 "/groups": {
      "get": {
        "summary": "Read Object(s)",
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "responses": {
          "200": {
            "description": "The requested resource"
          },
          "404": {
            "description": "Resource not found"
          },
          "500": {
            "description": "Internal server error"
          }
        },
        "tags": [
          "auth"
        ]
      }
    }

Parameters are missing in documentation.

I have actions , shortcuts and rest set to false on few controllers and updated routes.js for each method action (custom routes).
Now when i generate the documents its not having any information about the parameters (query Parameters).
Am i missing something ? why my documentation is missing Parameters section for all custom methods.
Plus i would like to know how to get more information about models , properties and methods ?
where i need to put that metadata ?

Note : When I added query Parameter information in routes its working

Is there library for converting js objects to valid Swagger spec?

Hi everyone!
I'm trying to connect waterline models in my sails project and swagger definitions for avoiding the duplications in models' properties.
My main idea is converting waterline's "attributes" property to valid swagger doc. For example, we have this object defined in models/User.js

module.exports = {
    model: "User", // add this field only for usage in swagger converter
    attributes: {
        local: {
            email: {
              type: 'string',
              required: true,
              swagger: {
                  description: "User's email"  // I'm not sure will waterline allow me use my own properties in fields' descriptors
              }
            },
            password:{
               type: 'string',
               required: true,
              swagger: {
                  description: "User's super secret password"
              }
            }
        }
    }
}

And after converting we would be able automagically get something like:

"User":{
  "id":"User",
  "required": ["email", "password"],
  "properties":{
    "id":{
      "type":"integer",
      "format": "int64",
      "description": "User unique identifier",
      "minimum": "0.0",
      "maximum": "100.0"
    },
    "email":{
      "type":"string",
      "description": "User's email"
    }, 
    "password":{
      "type":"string",
      "description": "User's super secret password"
    },
  }
},

I didn't manage to find something appropriate among this projects: https://github.com/swagger-api/swagger-spec#nodejs
If there is no such tool anywhere I will be happy to create first basic version :)

Thanks.

Cors origin is hard-coded

in the swagger config/routes the route is set to

'/swagger/doc': {
    cors: {
      origin: 'http://swagger.balderdash.io',
      methods: 'GET,OPTIONS,HEAD'
    },
    controller: 'SwaggerController',
    action: 'doc'
  }

even if change the route in my project's config/routes to

  '/swagger/doc': {
    cors: {
      origin: '*',
      methods: 'GET,OPTIONS,HEAD'
    },
    controller: 'SwaggerController',
    action: 'doc'
  }

it will not override the swagger config. for the time being I had to manually change the swagger node_module to actually let it other origins go through

Cannot read property 'pkg' of undefined

Using:

โœ” ~/PhpstormProjects/backoffice [master|โ—2โœš 2]
10:41 $ npm --version
3.3.5
โœ” ~/PhpstormProjects/backoffice [master|โ—2โœš 2]
10:42 $ node --version
v4.1.2
โœ” ~/PhpstormProjects/backoffice [master|โ—2โœš 2]
10:42 $ sails --version
0.11.0

I have this error:

info: Starting app...

debug: hookPath: /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/hooks/swagger
debug: marlinspike (swagger): loading config from /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/config
debug: marlinspike (swagger): loading Services from /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/services...
info: Error: ENOENT: no such file or directory, scandir '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/services'
    at Error (native)
    at Object.fs.readdirSync (fs.js:813:18)
    at requireAll (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/node_modules/require-all/index.js:12:18)
    at Swagger.loadServices (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/dist/marlinspike.js:129:52)
    at Hook.configure (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/dist/marlinspike.js:198:51)
    at Hook.bound [as configure] (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/loadHooks.js:176:18
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:122:13
    at _each (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:121:9)
    at Object.async.series.configure (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/loadHooks.js:174:17)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:620:25
    at iterate (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:157:25
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:626:21
    at done (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:132:19) { [Error: ENOENT: no such file or directory, scandir '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/services']
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/services' }
warn: marlinspike (swagger): no Services found. skipping
debug: marlinspike (swagger): loading Controllers...
debug: marlinspike (swagger): loading Policies...
info: Error: ENOENT: no such file or directory, scandir '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/policies'
    at Error (native)
    at Object.fs.readdirSync (fs.js:813:18)
    at requireAll (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/node_modules/require-all/index.js:12:18)
    at Swagger.loadPolicies (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/dist/marlinspike.js:93:52)
    at Hook.configure (/Users/davidportella/PhpstormProjects/backoffice/node_modules/marlinspike/dist/marlinspike.js:201:51)
    at Hook.bound [as configure] (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/loadHooks.js:176:18
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:122:13
    at _each (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:121:9)
    at Object.async.series.configure (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/loadHooks.js:174:17)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:620:25
    at iterate (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:157:25
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:626:21
    at done (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:132:19) { [Error: ENOENT: no such file or directory, scandir '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/policies']
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/policies' }
warn: marlinspike (swagger): no Policies found. skipping
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v0.11.2             |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `/Users/davidportella/PhpstormProjects/backoffice`
info: To see your app, visit http://localhost:1337
info: To shut down Sails, press <CTRL> + C at any time.

debug: --------------------------------------------------------
debug: :: Wed Oct 28 2015 10:41:26 GMT-0300 (CLT)

debug: Environment : development
debug: Port        : 1337
debug: --------------------------------------------------------
error: The bootstrap function threw an error after its callback was called :: TypeError: Cannot read property 'pkg' of undefined
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails-swagger/dist/api/hooks/swagger/index.js:49:91
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/after.js:91:14
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:251:17
    at done (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:132:19)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:32:16
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:248:21
    at Sails.<anonymous> (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:572:34)
    at Sails.g (events.js:260:16)
    at emitNone (events.js:67:13)
    at Sails.emit (events.js:166:7)
    at Sails.emitter.emit (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/after.js:50:11)
    at sailsReady (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/lift.js:47:11)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:251:17
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:154:25
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:248:21
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:612:34
    at afterBootstrap (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/initialize.js:57:5)
    at bootstrapDone (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/bootstrap.js:51:14)
    at Object.module.exports.bootstrap (/Users/davidportella/PhpstormProjects/backoffice/config/bootstrap.js:2:5)
    at Sails.runBootstrap (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/bootstrap.js:44:25)
    at Sails.bound [as runBootstrap] (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at Sails.initialize (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/private/initialize.js:48:9)
    at bound (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:607:21
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:246:17
    at iterate (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:146:13)
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:157:25
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:248:21
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:612:34
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/lib/app/load.js:201:13
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:451:17
    at /Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:441:17
    at _each (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:46:13)
    at Immediate.taskComplete (/Users/davidportella/PhpstormProjects/backoffice/node_modules/sails/node_modules/async/lib/async.js:440:13)
    at processImmediate [as _immediateCallback] (timers.js:374:17) [TypeError: Cannot read property 'pkg' of undefined]

Add options to select which routes should be documented

Today, all routes are added to the swagger document.
A user should be allowed to select what kind of routes he wants to document:

  • blueprints RESTful routes
  • blueprints shortcuts routes
  • blueprints actions routes
  • manual routes

One may want to document the REST API of the application and not necessarily want to expose the documentation of the requests to get HTML pages.

It could be an array with these default values:

sails.config.swagger.route: ['rest', 'shortcuts', 'blueprint_actions', 'manual']

Maybe the options could be limited to ['rest', 'shortcuts', 'actions'] where 'actions' stands for blueprint_actions and manual.

I guess it would be easier to implement this when sails.getRoutes() is available.

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.