deploymentwebpack-productionswagger-tools

Swagger Tools Production Build Node js


We implemented the swagger in our nodeJs application. As of now we are created production build using webpack and remove the controller and services file.

bin/www.js

const YAML = require('yamljs');
const swaggerTools = require('swagger-tools');
const swaggerDoc = YAML.safeLoad('./swagger.yaml');

// swaggerRouter configuration
const swaggerOptions = {
  controllers: path.join(__dirname, '../public/javascripts/controllers'),
  useStubs: true, // Conditionally turn on stubs (mock mode)
};


// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, (middleware) => {
  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // validate the security using JWT token
  app.use(middleware.swaggerSecurity({
      Bearer: auth.verifyToken
  }));
  // Validate Swagger requests
  app.use(middleware.swaggerValidator({
    validateResponse: true
  }));

  // Route validated requests to appropriate controller
  app.use(middleware.swaggerRouter(swaggerOptions));

  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi());

});

If we did the same in production build and the swagger middleware expecting the same path to resolve. after build we delete the public folder.

Webpack code

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    server: './bin/www',
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: 'server.build.js',
  },
  target: 'node',
  node: {
    // Need this when working with express, otherwise the build fails
    __dirname: false, // if you don't put this is, __dirname
    __filename: false, // and __filename return blank or /
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        // Transpiles ES6-8 into ES5
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
};

Pleas help us to create a build using swagger middleware

Thanks in advance


Solution

  • Swagger tools is not a package bundler like webpack. So you will still need to provide it the controller files. Since you are deleting /public from prod then there is no way for swagger tools middleware to get the files it needs. Webpack in this case is basically building a dist from your code which is why it's ok to delete the controller and services.