express-jsdoc-swagger

repository·master·Indexed 42 days ago

https://github.com/brikev/express-jsdoc-swagger

A Swagger OpenAPI 3.x generator for Express.js that allows developers to document APIs directly within JSDoc comments. It automatically generates Swagger UI and OpenAPI JSON documentation, eliminating the need for manual YAML or JSON maintenance. Version 1.8.1 supports defining endpoints with tags like @summary, @param, and @return, as well as reusable data models using @typedef.

Tokens
2.6K
Snippets
8
Records
9
Agent score
51%

What's inside express-jsdoc-swagger

  1. Validate API requests and responses with express-oas-validator

    master

    You can use express-oas-validator to ensure incoming requests and outgoing responses match your JSDoc documentation.

    Because the validator requires the full Swagger schema, you must wait for the express-jsdoc-swagger instance to finish generating the definition. You can do this by listening to the finish event on the instance.

    1. Install the validator: npm install --save express-oas-validator.
    2. Create a wrapper that waits for the finish event on the expressJSDocSwagger instance.
    3. Use validateRequest() as middleware for routes.
    4. Use validateResponse(message, req) inside route handlers to validate the response body.
    const { init } = require('express-oas-validator');
    
    // Helper to wait for swagger definition
    const waitForValidator = instance => new Promise((resolve, reject) => {
      instance.on('finish', (swaggerDef) => {
        const { validateRequest, validateResponse } = init(swaggerDef);
        resolve({ validateRequest, validateResponse });
      });
      instance.on('error', reject);
    });
    
    // Usage in server setup
    const instance = expressJSDocSwagger(app)(options);
    
    const serverApp = async () => {
      const { validateRequest, validateResponse } = await waitForValidator(instance);
      
      /**
       * POST /api/v1/songs
       * @param {Song} request.body.required - song info
       * @return {object} 200 - song response
       */
      app.post('/api/v1/songs', validateRequest(), (req, res) => res.send('Saved!'));
    
      /**
       * POST /api/v1/name
       * @param {string} request.body.required - name
       * @return {object} 200 - success
       */
      app.post('/api/v1/name', (req, res, next) => {
        try {
          validateResponse('Error string', req);
          return res.send('Hello!');
        } catch (error) {
          return next(error);
        }
      });
    };
  2. Set up the TS-Example project

    master

    To use the TypeScript example provided in this repository, install the project dependencies using npm.

    Important Configuration Note: When configuring express-jsdoc-swagger, ensure you include both ts and js extensions in your configuration. This is necessary because the application watches .ts files during development (using ts-node), but requires watching .js files when running the compiled production build.

    npm i
  3. Document endpoints using JSDoc

    master

    You can document endpoints by adding JSDoc comments above your Express route handlers. The library parses these comments to generate OpenAPI documentation.

    Common JSDoc tags used:

    • @summary: A brief description of the endpoint.
    • @tags: Group endpoints under specific categories.
    • @param: Defines parameters. Use the syntax {type} name.{location}.{required} - description. Locations include path, query, header, or body.
    • @return: Defines the response. Syntax: {type} {status_code} - description - content_type.
    • @security: References a security scheme defined in the configuration.
    • @typedef: Defines reusable data models (components).
    • @example: Provides a code example for a specific response status code.
    /**
     * GET /api/v1/albums/{id}
     * @summary Update album
     * @tags album
     * @param {string} id.path - The album ID
     * @param {Song} request.body.required - songs info
     * @return {array<Song>} 200 - success response - application/json
     */
    app.put('/api/v1/albums/:id', (req, res) => {
      // implementation
    });
  4. Run the TS-Example application

    master

    The TS-Example provides several scripts to manage the development lifecycle, including running in development mode with ts-node, building the TypeScript files, and running the production build.

    # Execute dev mode
    npm run dev
    
    # Build TS file in build/simple.js
    npm run tsc:build
    
    # Execute ts-node app
    npm run start
    
    # execute build app
    npm run start:prod
  5. Configure express-jsdoc-swagger

    master

    To use the library, pass your Express app instance to expressJSDocSwagger(app) and then call it with an options object.

    Key configuration options include:

    • info: Object containing API metadata like version, title, and license.
    • security: Defines security schemes (e.g., BasicAuth).
    • baseDir: The directory used to locate JSDoc files.
    • filesPattern: A glob pattern (string or array of strings) to find JSDoc files.
    • swaggerUIPath: The URL path where the Swagger UI will be rendered.
    • exposeSwaggerUI: Boolean to enable/disable Swagger UI.
    • exposeApiDocs: Boolean to enable/disable the OpenAPI JSON documentation.
    • apiDocsPath: The path for the OpenAPI JSON documentation.
    • swaggerUiOptions: Object to customize swagger-ui-express configuration.
    • multiple: Boolean to allow multiple instances.
    const express = require('express');
    const expressJSDocSwagger = require('express-jsdoc-swagger');
    
    const app = express();
    const options = {
      info: {
        version: '1.0.0',
        title: 'My API',
        license: { name: 'MIT' },
      },
      baseDir: __dirname,
      filesPattern: './**/*.js',
      swaggerUIPath: '/api-docs',
      exposeSwaggerUI: true,
    };
    
    expressJSDocSwagger(app)(options);
    
    app.listen(3000);
  6. Define reusable components with @typedef

    master

    Use the @typedef tag to define complex objects that can be reused across multiple endpoints as models.

    /**
     * A song type
     * @typedef {object} Song
     * @property {string} title.required - The title
     * @property {string} artist - The artist
     * @property {number} year - The year
     */
  7. Configure Swagger UI and API documentation exposure

    master

    When initializing express-jsdoc-swagger, you can control how the documentation is served using the following options:

    • exposeSwaggerUI: Boolean. If true, the library mounts swagger-ui-express to provide a visual documentation interface.
    • swaggerUIPath: String. The path where the Swagger UI will be served (e.g., '/docs').
    • swaggerUiOptions: Object. Options passed directly to swagger-ui-express.
    • exposeApiDocs: Boolean. If true, the library mounts a JSON endpoint containing the generated Swagger specification.
    • apiDocsPath: String. The path where the raw Swagger JSON will be served (e.g., '/api-docs').
  8. Initialize express-jsdoc-swagger in an Express application

    master

    The expressJSDocSwagger function is the main entrypoint for integrating the library into an Express application. It follows a higher-order function pattern: you pass the Express app instance to the main function, which returns a configuration function. This returned function accepts userOptions and userSwagger to initialize the Swagger documentation processing.

    Workflow:

    1. Call expressJSDocSwagger(app) to get the initializer.
    2. Call the initializer with your configuration and any manual Swagger object overrides.
    3. The library processes JSDoc comments, merges them with your manual Swagger object, and triggers lifecycle events.

    Key Features:

    • Swagger UI: If exposeSwaggerUI is enabled in options, the library automatically mounts Swagger UI at the configured swaggerUIPath.
    • API Docs JSON: If exposeApiDocs is enabled, the library mounts a GET route at apiDocsPath that returns the generated Swagger JSON.
    • Lifecycle Events: The library provides an instance (via the returned function) that allows you to hook into events like processFile, finish, and error.
    const express = require('express');
    const expressJSDocSwagger = require('express-jsdoc-swagger');
    
    const app = express();
    
    // 1. Initialize the middleware with the app instance
    const initSwagger = expressJSDocSwagger(app);
    
    // 2. Configure and run the initialization
    initSwagger(
      {
        exposeSwaggerUI: true,
        swaggerUIPath: '/docs',
        exposeApiDocs: true,
        apiDocsPath: '/api-docs'
      },
      { /* manual swagger object overrides */ }
    );
    
    app.listen(3000);