Patch middleware integration in swagger nodejs restag application?

I recently started learning swagger for a nodejs express application. As I understand it, swagger is a kind of structure that requires conventions to be executed in a nodejs express application. Swagger automatically maps routes to controllers.

But I feel that I have lost the ability to enter middlewares, for example, an authentication passport, which can easily be added to user routes.

I know that there are ways to introduce averages with swagger, but for some reason I feel that this is not as natural as without swagger.

Is it possible to use swagger with minimal swagger related components in my code - perhaps only with the swagger.yaml file?

I want to avoid the req.swagger.param code and want to use the standard way of determining routes and injecting middleware.

+4
source share
1 answer

Swagger itself is a middleware. When you start your application, swagger will register using app.Use ([swaggerMiddlewareObject]). This way you can add other middlwares before / after swagger.

Please find the comment below. You will have to change it based on your authentication strategy.

'use strict';

var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var passport = require('passport');

module.exports = app; // for testing

var config = {
  appRoot: __dirname // required config
};

/*Mount your passport Middleware here using app object. As your are building a stateless restful api, I assume you would use jwt
* 1. import jwt-strategy.
* 2. Configure passport to use jwt strategy.
* 3. app.use(passport.initialize());
* 4. app.use('/pathYouWantProtect', passport.authenticate('jwt-strategy'),function(req,res,next){
*       
*    });
*/

SwaggerExpress.create(config, function(err, swaggerExpress) {
  if (err) { throw err; }

  // install middleware
  swaggerExpress.register(app);

  var port = process.env.PORT || 10010;
  app.listen(port);

  if (swaggerExpress.runner.swagger.paths['/hello']) {
    console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
  }
});
+4
source

All Articles