Skip to content
This repository has been archived by the owner on Aug 4, 2023. It is now read-only.

app.use(middleware.swaggerRouter(options)) Not working #328

Closed
Dugnist opened this issue Jan 22, 2016 · 4 comments
Closed

app.use(middleware.swaggerRouter(options)) Not working #328

Dugnist opened this issue Jan 22, 2016 · 4 comments

Comments

@Dugnist
Copy link

Dugnist commented Jan 22, 2016

i use approximately this construction:

import http from 'http'
import express from 'express'
import swaggerTools from 'swagger-tools'

const app = express()
const port = process.env.PORT || 3001

var options = {
    controllers: './controllers',
    useStubs: process.env.NODE_ENV === 'development' ? false : true // Conditionally turn on stubs (mock mode)
}

var swaggerDoc = require('./api/swagger.json')

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
    // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
    app.use(middleware.swaggerMetadata())
    // Validate Swagger requests
    app.use(middleware.swaggerValidator())
    // Route validated requests to appropriate controller
        console.log('before')
    app.use(middleware.swaggerRouter(options))
        console.log('after')
    // Serve the Swagger documents and Swagger UI
    app.use(middleware.swaggerUi())
})

http.createServer( app ).listen( port, function ( err ) {
    console.log('listening in http://localhost:' + port)
})

console give me 'before' but not give 'after'...
dir ./controllers exist and have example file Weather.js

at node_modules/swagger-tools/middleware/swagger-router.js i put console.log, and it works before string

if (_.isPlainObject(options.controllers)) {

and not working after her...

To be more precise:

_.each(dirs, function (dir) {
    console.log(dir);
    _.each(fs.readdirSync(dir), function (file) {
      console.log(file);

first log - give ./controllers
second - none

Please help...

@whitlockjc
Copy link
Member

Run using DEBUG=swagger-tools* node . and let me know the output. Nothing has changed in swagger-router for some time so I'm not sure where to start without some extra information.

@Dugnist
Copy link
Author

Dugnist commented Jan 22, 2016

I run it and have nothing alert :(
Maybe u faster find the problem in my code there:
https://github.com/Peekab0o/swagger-mocha-s3fs

/server
app.js - es6
api.js - es5
I will be very grateful...

@whitlockjc
Copy link
Member

I had to change your npm start to use DEBUG=swagger-tools* instead of DEBUG=swagger-tools. That gives me this:

body-parser deprecated bodyParser: use individual json/urlencoded middlewares server/app.js:87:37
body-parser deprecated undefined extended: provide extended option node_modules/body-parser/index.js:105:29
  swagger-tools:middleware Initializing middleware +0ms
  swagger-tools:middleware   Identified Swagger version: 2.0 +2ms
  swagger-tools:middleware   Validation: succeeded +52ms
  swagger-tools:middleware:metadata Initializing swagger-metadata middleware +51ms
  swagger-tools:middleware:metadata   Identified Swagger version: 2.0 +0ms
  swagger-tools:middleware:metadata   Found Path: /document +2ms
  swagger-tools:middleware:validator Initializing swagger-validator middleware +1ms
  swagger-tools:middleware:validator   Response validation: disabled +0ms
before
  swagger-tools:middleware:router Initializing swagger-router middleware +0ms
  swagger-tools:middleware:router   Mock mode: disabled +0ms
  swagger-tools:middleware:router   Controllers: +1ms
listening in http://localhost:3001
Connected to database documents

This tells me it didn't find any controllers. Upon looking into why, I found. It's related to #327. swagger-router is throwing an error that ./controllers does not exist but you don't see it because #327 points out that errors are being swallowed. I'm currently working on this and will close it so we can follow there.

@whitlockjc
Copy link
Member

Your server code is also somewhat to blame. You're calling initializeMiddleware as if it's synchronous and running other code outside of it. So while your server appears to run fine, it's actually erroring. Here are my changes to your project to make it fail startup when swagger-tools encounters an error:

diff --git a/package.json b/package.json
index 7d9b922..7320a2d 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
   "repository": "git://github.com/auth0/auth0-nodejsapi-sample",
   "author": "Auth0",
   "scripts": {
-    "start": "DEBUG=swagger-tools babel-node server/app"
+    "start": "DEBUG=swagger-tools* babel-node server/app"
   },
   "license": "MIT",
   "engines": {
diff --git a/server/app.js b/server/app.js
index 5bba416..db22e9b 100755
--- a/server/app.js
+++ b/server/app.js
@@ -12,6 +12,9 @@ import requireDir from 'require-dir'
 import bodyParser from 'body-parser'
 import compression from 'compression'
 import swaggerTools from 'swagger-tools'
+import JSONP from 'node-jsonp'
+
+import db from './core/driver'

 /**
  * Set the start parameters
@@ -24,12 +27,6 @@ const port = process.env.PORT || 3001
 /**
  * db connection
  */
-
-mongoose.connect('mongodb://root:dadadada@ds047865.mongolab.com:47865/documents',
-function () {
-   console.log( 'Connected to database documents' )
-})
-
 /**
  * Configure app
  */
@@ -54,7 +51,6 @@ app.use( express.static( path.join(__dirname, '../dist' ) ))
 const showIndexContent = function response( req, res ) {
    res.sendFile( path.join( __dirname, '../dist' ) )
 }
-app.get( '/', showIndexContent )

 /**
  * Require routes
@@ -81,137 +77,137 @@ console.log('after')
    // Serve the Swagger documents and Swagger UI
    app.use(middleware.swaggerUi())

+   mongoose.connect('mongodb://root:dadadada@ds047865.mongolab.com:47865/documents',
+   function () {
+       console.log( 'Connected to database documents' )
+   })

-})
-
-http.createServer( app ).listen( port, function ( err ) {
-   console.log('listening in http://localhost:' + port)
-})
-
-
-import JSONP from 'node-jsonp'
+   app.get( '/', showIndexContent )

-//****
-// GET Document
-//****
-app.post('/cors', function( req, res ) {
+   //****
+   // GET Document
+   //****
+   app.post('/cors', function( req, res ) {

-       JSONP( req.body.url ,function(json){
-           console.log(json)
-           res.status(200).send( json )
-       })
-})
+           JSONP( req.body.url ,function(json){
+               console.log(json)
+               res.status(200).send( json )
+           })
+   })





-// TODO:
-// for ( i of routes ) {
-//   app.use( '/api/', routes[ i ] )
-// }
+   // TODO:
+   // for ( i of routes ) {
+   //   app.use( '/api/', routes[ i ] )
+   // }
+   var Document = new db('document')

-import db from './core/driver'
-var Document = new db('document')
-
-//****
-// GET Document
-//****
-app.get('/weather', function( req, res ) {
-   let newDocument = {
-       document_collection: {
-           entries:[
-               { type: 'document',
-                   id: '3230d79822b04e22ac77b255e4b48283',
-                   status: 'done',
-                   name: 'kjlkjlk',
-                   date: '2016-01-21T17:30:27Z'
-               }
-           ]
+   //****
+   // GET Document
+   //****
+   app.get('/weather', function( req, res ) {
+       let newDocument = {
+           document_collection: {
+               entries:[
+                   { type: 'document',
+                       id: '3230d79822b04e22ac77b255e4b48283',
+                       status: 'done',
+                       name: 'kjlkjlk',
+                       date: '2016-01-21T17:30:27Z'
+                   }
+               ]
+           }
        }
-   }
-   if( req.headers.authorization ){
-       res.status(200).send( newDocument )
-   } else {
-       res.status(401).send({ response: "Unauthorized request" })
-   }
-})
+       if( req.headers.authorization ){
+           res.status(200).send( newDocument )
+       } else {
+           res.status(401).send({ response: "Unauthorized request" })
+       }
+   })

-//****
-// View all Documents
-//****
-app.post('/secured/Documents', function( req, res ) {
-   Document.getAll( function( err, result ){
-       res.send(200, JSON.stringify( result ) ) // res
+   //****
+   // View all Documents
+   //****
+   app.post('/secured/Documents', function( req, res ) {
+       Document.getAll( function( err, result ){
+           res.send(200, JSON.stringify( result ) ) // res
+       })
    })
-})

-//****
-// View one Document
-//****
-app.post('/secured/Document/569cfd0d459347f9230bc7d7', function( req, res ) {
-   Document.getById( "569cfd0d459347f9230bc7d7", function( err, result ){
-       res.send(200, result ) // res
+   //****
+   // View one Document
+   //****
+   app.post('/secured/Document/569cfd0d459347f9230bc7d7', function( req, res ) {
+       Document.getById( "569cfd0d459347f9230bc7d7", function( err, result ){
+           res.send(200, result ) // res
+       })
    })
-})

-//****
-// Edit Document
-//****
-app.put('/secured/Document', function( req, res ) {
-   let updatedDocument = {
-       Documentname: req.body.name,
-       login: req.body.login,
-       mail: req.body.mail,
-       id: req.body.id
-   }
-   Document.update( updatedDocument, function( cb ){
-       console.log( cb+'1' ) // null
-       res.send(200, "Welcome: " )
+   //****
+   // Edit Document
+   //****
+   app.put('/secured/Document', function( req, res ) {
+       let updatedDocument = {
+           Documentname: req.body.name,
+           login: req.body.login,
+           mail: req.body.mail,
+           id: req.body.id
+       }
+       Document.update( updatedDocument, function( cb ){
+           console.log( cb+'1' ) // null
+           res.send(200, "Welcome: " )
+       })
    })
-})

-//****
-// Delete Document
-//****
-app.delete('/secured/Document', function( req, res ) {
-   Document.delete( { id: req.body.id }, function( cb ){
-       console.log( cb ) // null
-       res.send(200, "success" )
+   //****
+   // Delete Document
+   //****
+   app.delete('/secured/Document', function( req, res ) {
+       Document.delete( { id: req.body.id }, function( cb ){
+           console.log( cb ) // null
+           res.send(200, "success" )
+       })
    })
-})

-/**
- * Profile
- */
+   /**
+    * Profile
+    */

-app.post('/secured/profile', function( req, res ) {
+   app.post('/secured/profile', function( req, res ) {

-   console.log( req.body.client_id )
+       console.log( req.body.client_id )

-   Document.getOne( { token: req.body.client_id },function( err, result ){
-       console.log( result )
-       if ( result === null ) {
-           let newDocument = {
-               Documentname: req.body.name,
-               token: req.body.client_id,
-               login: req.body.login,
-               mail: req.body.mail
+       Document.getOne( { token: req.body.client_id },function( err, result ){
+           console.log( result )
+           if ( result === null ) {
+               let newDocument = {
+                   Documentname: req.body.name,
+                   token: req.body.client_id,
+                   login: req.body.login,
+                   mail: req.body.mail
+               }
+               console.log( newDocument )
+               Document.save( newDocument, function( cb ){
+                   console.log( cb ) // null
+               })
            }
-           console.log( newDocument )
-           Document.save( newDocument, function( cb ){
-               console.log( cb ) // null
-           })
-       }
+       })
+       res.send(200, { access: "allowed" } )
+
    })
-   res.send(200, { access: "allowed" } )

-})
+   http.createServer( app ).listen( port, function ( err ) {
+       console.log('listening in http://localhost:' + port)
+   })

-/**
- * Listen port
- */
+   /**
+    * Listen port
+    */

-// http.createServer( app ).listen( port, function ( err ) {
-//     console.log('listening in http://localhost:' + port)
-// })
+   // http.createServer( app ).listen( port, function ( err ) {
+   //  console.log('listening in http://localhost:' + port)
+   // })
+})

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants